Merge pull request #85 from matiu/feature/optimizations

Feature/optimizations -- great jobs!
This commit is contained in:
Gustavo Maximiliano Cortez 2014-05-26 10:15:04 -03:00
commit cb1861f10f
20 changed files with 2773 additions and 1140 deletions

View File

@ -5,9 +5,11 @@
*/
var common = require('./common'),
async = require('async'),
BlockDb = require('../../lib/BlockDb');
BlockDb = require('../../lib/BlockDb'),
TransactionDb = require('../../lib/TransactionDb');
var bdb = new BlockDb();
var tdb = new TransactionDb();
/**
* Find block by hash ...
@ -17,7 +19,7 @@ exports.block = function(req, res, next, hash) {
if (err || !block)
return common.handleErrors(err, res, next);
else {
bdb.getPoolInfo(block.info.tx[0], function(info) {
tdb.getPoolInfo(block.info.tx[0], function(info) {
block.info.poolInfo = info;
req.block = block.info;
return next();
@ -67,7 +69,7 @@ var getBlock = function(blockhash, cb) {
};
}
bdb.getPoolInfo(block.info.tx[0], function(info) {
tdb.getPoolInfo(block.info.tx[0], function(info) {
block.info.poolInfo = info;
return cb(err, block.info);
});

View File

@ -32,10 +32,10 @@ module.exports.broadcastTx = function(tx) {
// Outputs
var valueOut = 0;
tx.vout.forEach(function(o) {
valueOut += o.value * util.COIN;
valueOut += o.valueSat;
});
t.valueOut = parseInt(valueOut) / util.COIN;
t.valueOut = (valueOut/util.COIN).toFixed(0);
}
ios.sockets.in('inv').emit('tx', t);
}

View File

@ -9,6 +9,8 @@ var BitcoreUtil = bitcore.util;
var Parser = bitcore.BinaryParser;
var Buffer = bitcore.Buffer;
var TransactionDb = imports.TransactionDb || require('../../lib/TransactionDb').default();
var BlockDb = imports.BlockDb || require('../../lib/BlockDb').default();
var config = require('../../config/config');
var CONCURRENCY = 5;
function Address(addrStr) {
@ -20,6 +22,7 @@ function Address(addrStr) {
this.txApperances = 0;
this.unconfirmedTxApperances= 0;
this.seen = {};
// TODO store only txids? +index? +all?
this.transactions = [];
@ -71,125 +74,123 @@ function Address(addrStr) {
}
Address.prototype._getScriptPubKey = function(hex,n) {
// ScriptPubKey is not provided by bitcoind RPC, so we parse it from tx hex.
var parser = new Parser(new Buffer(hex,'hex'));
var tx = new BitcoreTransaction();
tx.parse(parser);
return (tx.outs[n].s.toString('hex'));
};
Address.prototype.getUtxo = function(next) {
var self = this;
if (!self.addrStr) return next();
var tDb = TransactionDb;
var bDb = BlockDb;
var ret;
if (!self.addrStr) return next(new Error('no error'));
var ret = [];
var db = TransactionDb;
db.fromAddr(self.addrStr, function(err,txOut){
tDb.fromAddr(self.addrStr, function(err,txOut){
if (err) return next(err);
var unspent = txOut.filter(function(x){
return !x.spentTxId;
});
// Complete utxo info
async.eachLimit(txOut,CONCURRENCY,function (txItem, a_c) {
db.fromIdInfoSimple(txItem.txid, function(err, info) {
if (!info || !info.hex) return a_c(err);
var scriptPubKey = self._getScriptPubKey(info.hex, txItem.index);
// we are filtering out even unconfirmed spents!
// add || !txItem.spentIsConfirmed
if (!txItem.spentTxId) {
ret.push({
bDb.fillConfirmations(unspent, function() {
tDb.fillScriptPubKey(unspent, function() {
ret = unspent.map(function(x){
return {
address: self.addrStr,
txid: txItem.txid,
vout: txItem.index,
ts: txItem.ts,
scriptPubKey: scriptPubKey,
amount: txItem.value_sat / BitcoreUtil.COIN,
confirmations: txItem.isConfirmed ? info.confirmations : 0,
});
}
return a_c(err);
txid: x.txid,
vout: x.index,
ts: x.ts,
scriptPubKey: x.scriptPubKey,
amount: x.value_sat / BitcoreUtil.COIN,
confirmations: x.isConfirmedCached ? (config.safeConfirmations+'+') : x.confirmations,
};
});
return next(null, ret);
});
}, function(err) {
return next(err,ret);
});
});
};
Address.prototype._addTxItem = function(txItem, notxlist) {
var add=0, addSpend=0;
var v = txItem.value_sat;
var seen = this.seen;
var txs = [];
if ( !seen[txItem.txid] ) {
if (!notxlist) {
txs.push({txid: txItem.txid, ts: txItem.ts});
}
seen[txItem.txid]=1;
add=1;
}
if (txItem.spentTxId && !seen[txItem.spentTxId] ) {
if (!notxlist) {
txs.push({txid: txItem.spentTxId, ts: txItem.spentTs});
}
seen[txItem.spentTxId]=1;
addSpend=1;
}
if (txItem.isConfirmed) {
this.txApperances += add;
this.totalReceivedSat += v;
if (! txItem.spentTxId ) {
//unspent
this.balanceSat += v;
}
else if(!txItem.spentIsConfirmed) {
// unspent
this.balanceSat += v;
this.unconfirmedBalanceSat -= v;
this.unconfirmedTxApperances += addSpend;
}
else {
// spent
this.totalSentSat += v;
this.txApperances += addSpend;
}
}
else {
this.unconfirmedBalanceSat += v;
this.unconfirmedTxApperances += add;
}
return txs;
};
Address.prototype._setTxs = function(txs) {
// sort input and outputs togheter
txs.sort(
function compare(a,b) {
if (a.ts < b.ts) return 1;
if (a.ts > b.ts) return -1;
return 0;
});
this.transactions = txs.map(function(i) { return i.txid; } );
};
Address.prototype.update = function(next, notxlist) {
var self = this;
if (!self.addrStr) return next();
var txs = [];
var db = TransactionDb;
async.series([
function (cb) {
var seen={};
db.fromAddr(self.addrStr, function(err,txOut){
if (err) return cb(err);
var tDb = TransactionDb;
var bDb = BlockDb;
tDb.fromAddr(self.addrStr, function(err,txOut){
if (err) return next(err);
bDb.fillConfirmations(txOut, function(err) {
if (err) return next(err);
tDb.cacheConfirmations(txOut, function(err) {
if (err) return next(err);
txOut.forEach(function(txItem){
var add=0, addSpend=0;
var v = txItem.value_sat;
if ( !seen[txItem.txid] ) {
if (!notxlist) {
txs.push({txid: txItem.txid, ts: txItem.ts});
}
seen[txItem.txid]=1;
add=1;
}
if (txItem.spentTxId && !seen[txItem.spentTxId] ) {
if (!notxlist) {
txs.push({txid: txItem.spentTxId, ts: txItem.spentTs});
}
seen[txItem.spentTxId]=1;
addSpend=1;
}
if (txItem.isConfirmed) {
self.txApperances += add;
self.totalReceivedSat += v;
if (! txItem.spentTxId ) {
//unspent
self.balanceSat += v;
}
else if(!txItem.spentIsConfirmed) {
// unspent
self.balanceSat += v;
self.unconfirmedBalanceSat -= v;
self.unconfirmedTxApperances += addSpend;
}
else {
// spent
self.totalSentSat += v;
self.txApperances += addSpend;
}
}
else {
self.unconfirmedBalanceSat += v;
self.unconfirmedTxApperances += add;
}
txs=txs.concat(self._addTxItem(txItem, notxlist));
});
return cb();
if (!notxlist)
self._setTxs(txs);
return next();
});
},
], function (err) {
if (!notxlist) {
// sort input and outputs togheter
txs.sort(
function compare(a,b) {
if (a.ts < b.ts) return 1;
if (a.ts > b.ts) return -1;
return 0;
});
self.transactions = txs.map(function(i) { return i.txid; } );
}
return next(err);
});
});
};

View File

@ -91,5 +91,6 @@ module.exports = {
currencyRefresh: 10,
keys: {
segmentio: process.env.INSIGHT_SEGMENTIO_KEY
}
},
safeConfirmations: 6, // PLEASE NOTE THAT *FULL RESYNC* IS NEEDED TO CHANGE safeConfirmations
};

1328
dev-util/node-tick-report Normal file

File diff suppressed because it is too large Load Diff

View File

@ -58,3 +58,13 @@ first 10%
Mon Mar 10 11:59:25 ART 2014
10% de blk 0 (testnet)
=> 37s
Thu May 22 13:42:50 ART 2014 (base58check + toString opts + custom getStandardizedObject)
10% testnet
=> 29s
100% testnet
=> 17m6s (user time)

View File

@ -1,16 +1,20 @@
'use strict';
var imports = require('soop').imports();
var ThisParent = imports.parent || require('events').EventEmitter;
var TIMESTAMP_PREFIX = 'bts-'; // b-ts-<ts> => <hash>
var PREV_PREFIX = 'bpr-'; // b-prev-<hash> => <prev_hash>
var NEXT_PREFIX = 'bne-'; // b-next-<hash> => <next_hash>
var MAIN_PREFIX = 'bma-'; // b-main-<hash> => 1/0
var TIP = 'bti-'; // last block on the chain
var TIMESTAMP_PREFIX = 'bts-'; // bts-<ts> => <hash>
var PREV_PREFIX = 'bpr-'; // bpr-<hash> => <prev_hash>
var NEXT_PREFIX = 'bne-'; // bne-<hash> => <next_hash>
var MAIN_PREFIX = 'bma-'; // bma-<hash> => <height> (0 is unconnected)
var TIP = 'bti-'; // bti = <hash>:<height> last block on the chain
var LAST_FILE_INDEX = 'file-'; // last processed file index
var MAX_OPEN_FILES = 500;
// txid - blockhash mapping (only for confirmed txs, ONLY FOR BEST BRANCH CHAIN)
var IN_BLK_PREFIX = 'btx-'; //btx-<txid> = <block>
var MAX_OPEN_FILES = 500;
var CONCURRENCY = 5;
var DFLT_REQUIRED_CONFIRMATIONS = 1;
/**
* Module dependencies.
*/
@ -18,15 +22,18 @@ var levelup = require('levelup'),
config = require('../config/config');
var db = imports.db || levelup(config.leveldb + '/blocks',{maxOpenFiles: MAX_OPEN_FILES} );
var Rpc = imports.rpc || require('./Rpc');
var PoolMatch = imports.poolMatch || require('soop').load('./PoolMatch',config);
var async = require('async');
var tDb = require('./TransactionDb.js').default();
var BlockDb = function() {
var logger = require('./logger').logger;
var d = logger.log;
var info = logger.info;
var BlockDb = function(opts) {
this.txDb = require('./TransactionDb').default();
this.safeConfirmations = config.safeConfirmations || DEFAULT_SAFE_CONFIRMATIONS;
BlockDb.super(this, arguments);
this.poolMatch = new PoolMatch();
};
BlockDb.parent = ThisParent;
BlockDb.prototype.close = function(cb) {
db.close(cb);
@ -42,38 +49,146 @@ BlockDb.prototype.drop = function(cb) {
});
};
// adds a block. Does not update Next pointer in
// the block prev to the new block, nor TIP pointer
//
BlockDb.prototype.add = function(b, cb) {
var self = this;
BlockDb.prototype._addBlockScript = function(b, height) {
var time_key = TIMESTAMP_PREFIX +
( b.time || Math.round(new Date().getTime() / 1000) );
return db.batch()
.put(time_key, b.hash)
.put(MAIN_PREFIX + b.hash, 1)
.put(PREV_PREFIX + b.hash, b.previousblockhash)
.write(function(err){
if (!err) {
self.emit('new_block', {blockid: b.hash});
}
cb(err);
});
return [
{
type: 'put',
key: time_key,
value: b.hash,
},
{
type: 'put',
key: MAIN_PREFIX + b.hash,
value: height,
},
{
type: 'put',
key:PREV_PREFIX + b.hash,
value: b.previousblockhash,
},
];
};
BlockDb.prototype.getTip = function(cb) {
db.get(TIP, function(err, val) {
return cb(err,val);
BlockDb.prototype._delTxsScript = function(txs) {
var dbScript =[];
for(var ii in txs){
dbScript.push({
type: 'del',
key: IN_BLK_PREFIX + txs[ii],
});
}
return dbScript;
};
BlockDb.prototype._addTxsScript = function(txs, hash, height) {
var dbScript =[];
for(var ii in txs){
dbScript.push({
type: 'put',
key: IN_BLK_PREFIX + txs[ii],
value: hash+':'+height,
});
}
return dbScript;
};
// Returns blockHash and height for a given txId (If the tx is on the MAIN chain).
BlockDb.prototype.getBlockForTx = function(txId, cb) {
db.get(IN_BLK_PREFIX + txId,function (err, val) {
if (err && err.notFound) return cb();
if (err) return cb(err);
var v = val.split(':');
return cb(err,v[0],parseInt(v[1]));
});
};
BlockDb.prototype.setTip = function(hash, cb) {
db.put(TIP, hash, function(err) {
BlockDb.prototype._changeBlockHeight = function(hash, height, cb) {
var self = this;
var dbScript1 = this._setHeightScript(hash,height);
d('Getting TXS FROM %s to set it Main', hash);
this.fromHashWithInfo(hash, function(err, bi) {
if (!bi || !bi.info || !bi.info.tx)
throw new Error('unable to get info for block:'+ hash);
var dbScript2;
if (height>=0) {
dbScript2 = self._addTxsScript(bi.info.tx, hash, height);
info('\t%s %d Txs', 'Confirming', bi.info.tx.length);
} else {
dbScript2 = self._delTxsScript(bi.info.tx);
info('\t%s %d Txs', 'Unconfirming', bi.info.tx.length);
}
db.batch(dbScript2.concat(dbScript1),cb);
});
};
BlockDb.prototype.setBlockMain = function(hash, height, cb) {
this._changeBlockHeight(hash,height,cb);
};
BlockDb.prototype.setBlockNotMain = function(hash, cb) {
this._changeBlockHeight(hash,-1,cb);
};
// adds a block (and its txs). Does not update Next pointer in
// the block prev to the new block, nor TIP pointer
//
BlockDb.prototype.add = function(b, height, cb) {
d('adding block %s #d', b,height);
var dbScript = this._addBlockScript(b,height);
dbScript = dbScript.concat(this._addTxsScript(
b.tx.map(
function(o){
return o.txid;
}),
b.hash,
height
));
this.txDb.addMany(b.tx, function(err) {
if (err) return cb(err);
db.batch(dbScript,cb);
});
};
BlockDb.prototype.getTip = function(cb) {
if (this.cachedTip){
var v = this.cachedTip.split(':');
return cb(null,v[0], parseInt(v[1]));
}
var self = this;
db.get(TIP, function(err, val) {
if (!val) return cb();
self.cachedTip = val;
var v = val.split(':');
return cb(err,v[0], parseInt(v[1]));
});
};
BlockDb.prototype.setTip = function(hash, height, cb) {
this.cachedTip = hash + ':' + height;
db.put(TIP, this.cachedTip, function(err) {
return cb(err);
});
};
BlockDb.prototype.getDepth = function(hash, cb) {
var v = this.cachedTip.split(':');
if (!v) throw new Error('getDepth called with not cachedTip');
this.getHeight(hash, function(err,h){
return cb(err,parseInt(v[1]) - h);
});
};
//mainly for testing
BlockDb.prototype.setPrev = function(hash, prevHash, cb) {
db.put(PREV_PREFIX + hash, prevHash, function(err) {
@ -113,19 +228,22 @@ BlockDb.prototype.getNext = function(hash, cb) {
});
};
BlockDb.prototype.isMain = function(hash, cb) {
BlockDb.prototype.getHeight = function(hash, cb) {
db.get(MAIN_PREFIX + hash, function(err, val) {
if (err && err.notFound) { err = null; val = 0;}
return cb(err,parseInt(val));
});
};
BlockDb.prototype.setMain = function(hash, isMain, cb) {
if (!isMain) console.log('\tNew orphan: %s',hash);
db.put(MAIN_PREFIX + hash, isMain?1:0, function(err) {
return cb(err);
});
BlockDb.prototype._setHeightScript = function(hash, height) {
d('setHeight: %s #%d', hash,height);
return ([{
type: 'put',
key: MAIN_PREFIX + hash,
value: height,
}]);
};
BlockDb.prototype.setNext = function(hash, nextHash, cb) {
db.put(NEXT_PREFIX + hash, nextHash, function(err) {
return cb(err);
@ -160,34 +278,17 @@ BlockDb.prototype.has = function(hash, cb) {
});
};
BlockDb.prototype.getPoolInfo = function(tx, cb) {
var self = this;
tDb._getInfo(tx, function(e, a) {
if (e) return cb(false);
if (a && a.isCoinBase) {
var coinbaseHexBuffer = new Buffer(a.vin[0].coinbase, 'hex');
var aa = self.poolMatch.match(coinbaseHexBuffer);
return cb(aa);
}
else {
return cb();
}
});
};
BlockDb.prototype.fromHashWithInfo = function(hash, cb) {
var self = this;
Rpc.getBlock(hash, function(err, info) {
if (err || !info) return cb(err);
self.isMain(hash, function(err, val) {
//TODO can we get this from RPC .height?
self.getHeight(hash, function(err, height) {
if (err) return cb(err);
info.isMainChain = val ? true : false;
info.isMainChain = height ? true : false;
return cb(null, {
hash: hash,
@ -223,4 +324,64 @@ BlockDb.prototype.blockIndex = function(height, cb) {
return Rpc.blockIndex(height,cb);
};
BlockDb.prototype._fillConfirmationsOneSpent = function(o, chainHeight, cb) {
var self = this;
if (!o.spentTxId) return cb();
if (o.multipleSpentAttempts) {
async.eachLimit(o.multipleSpentAttempts, CONCURRENCY,
function(oi, e_c) {
self.getBlockForTx(oi.spentTxId, function(err, hash, height) {
if (err) return;
if (height>=0) {
o.spentTxId = oi.spentTxId;
o.index = oi.index;
o.spentIsConfirmed = chainHeight - height >= self.safeConfirmations ? 1 : 0;
o.spentConfirmations = chainHeight - height;
}
return e_c();
});
}, cb);
} else {
self.getBlockForTx(o.spentTxId, function(err, hash, height) {
if (err) return cb(err);
o.spentIsConfirmed = chainHeight - height >= self.safeConfirmations ? 1 : 0;
o.spentConfirmations = chainHeight - height;
return cb();
});
}
};
BlockDb.prototype._fillConfirmationsOne = function(o, chainHeight, cb) {
var self = this;
self.getBlockForTx(o.txid, function(err, hash, height) {
if (err) return cb(err);
o.isConfirmed = chainHeight - height >= self.safeConfirmations ? 1 : 0;
o.confirmations = chainHeight - height;
return self._fillConfirmationsOneSpent(o,chainHeight,cb);
});
};
BlockDb.prototype.fillConfirmations = function(txouts, cb) {
var self = this;
this.getTip(function(err, hash, height){
var txs = txouts.filter(function(x){
return !x.spentIsConfirmedCached // not 100%cached
&& !(x.isConfirmedCached && !x.spentTxId); // and not 50%cached but not spent
});
//console.log('[BlockDb.js.360:txouts:]',txs.length); //TODO
var i=0;
async.eachLimit(txs, CONCURRENCY, function(txout, e_c) {
if(txout.isConfirmedCached) {
//console.log('[BlockDb.js.378]', i++); //TODO
self._fillConfirmationsOneSpent(txout,height, e_c);
} else {
//console.log('[BlockDb.js.3782]', i++); //TODO
self._fillConfirmationsOne(txout,height, e_c);
}
}, cb);
});
};
module.exports = require('soop')(BlockDb);

View File

@ -2,24 +2,21 @@
var imports = require('soop').imports();
var util = require('util');
var assert = require('assert');
var async = require('async');
var bitcore = require('bitcore');
var RpcClient = bitcore.RpcClient;
var Script = bitcore.Script;
var networks = bitcore.networks;
var config = imports.config || require('../config/config');
var Sync = require('./Sync');
var sockets = require('../app/controllers/socket.js');
var BlockExtractor = require('./BlockExtractor.js');
var buffertools = require('buffertools');
var Address = bitcore.Address;
var bitcoreUtil = bitcore.util;
var logger = require('./logger').logger;
var info = logger.info;
var error = logger.error;
// var bitcoreUtil = require('bitcore/util/util');
// var Deserialize = require('bitcore/Deserialize');
var BAD_GEN_ERROR = 'Bad genesis block. Network mismatch between Insight and bitcoind? Insight is configured for:';
var BAD_GEN_ERROR_DB = 'Bad genesis block. Network mismatch between Insight and levelDB? Insight is configured for:';
@ -41,35 +38,26 @@ function HistoricSync(opts) {
this.sync = new Sync(opts);
}
function p() {
var args = [];
Array.prototype.push.apply(args, arguments);
args.unshift('[historic_sync]');
/*jshint validthis:true */
console.log.apply(this, args);
}
HistoricSync.prototype.showProgress = function() {
var self = this;
if ( self.status ==='syncing' &&
( self.syncedBlocks ) % self.step !== 1) return;
if (self.error) {
p('ERROR: ' + self.error);
}
if (self.error)
error(self.error);
else {
self.updatePercentage();
p(util.format('status: [%d%%]', self.syncPercentage));
info(util.format('status: [%d%%]', self.syncPercentage));
}
if (self.shouldBroadcast) {
sockets.broadcastSyncInfo(self.info());
}
// if (self.syncPercentage > 10) {
// process.exit(-1);
// }
//
// if (self.syncPercentage > 10) {
// process.exit(-1);
// }
};
@ -133,6 +121,23 @@ HistoricSync.prototype.getBlockFromRPC = function(cb) {
});
};
HistoricSync.prototype.getStandardizedBlock = function(b) {
var self = this;
var block = {
hash: bitcoreUtil.formatHashFull(b.getHash()),
previousblockhash: bitcoreUtil.formatHashFull(b.prev_hash),
time: b.timestamp,
};
var isCoinBase = 1;
block.tx = b.txs.map(function(tx){
var ret = self.sync.txDb.getStandardizedTx(tx, b.timestamp, isCoinBase);
isCoinBase=0;
return ret;
});
return block;
};
HistoricSync.prototype.getBlockFromFile = function(cb) {
var self = this;
@ -141,36 +146,7 @@ HistoricSync.prototype.getBlockFromFile = function(cb) {
//get Info
self.blockExtractor.getNextBlock(function(err, b) {
if (err || ! b) return cb(err);
blockInfo = b.getStandardizedObject(b.txs, self.network);
blockInfo.previousblockhash = blockInfo.prev_block;
var ti=0;
// Get TX Address
b.txs.forEach(function(t) {
var objTx = blockInfo.tx[ti++];
//add time from block
objTx.time = blockInfo.time;
var to=0;
t.outs.forEach( function(o) {
try {
var s = new Script(o.s);
var addrs = new Address.fromScriptPubKey(s, config.network);
// support only for p2pubkey p2pubkeyhash and p2sh
if (addrs.length === 1) {
objTx.out[to].addrStr = addrs[0];
}
} catch (e) {
console.log('WARN Could not processs: ' + objTx.txid ,e);
}
to++;
});
});
blockInfo = self.getStandardizedBlock(b);
self.sync.bDb.setLastFileIndex(self.blockExtractor.currentFileIndex, function(err) {
return cb(err,blockInfo);
});
@ -235,7 +211,7 @@ HistoricSync.prototype.updateStartBlock = function(next) {
self.sync.bDb.fromHashWithInfo(tip, function(err, bi) {
blockInfo = bi ? bi.info : {};
if (oldtip)
self.sync.setBlockMain(oldtip, false, cb);
self.sync.setBlockHeight(oldtip, -1, cb);
else
return cb();
});
@ -249,16 +225,18 @@ HistoricSync.prototype.updateStartBlock = function(next) {
}
else {
oldtip = tip;
if (!tip)
throw new Error('Previous blockchain tip was not found on bitcoind. Please reset Insight DB. Tip was:'+tip)
tip = blockInfo.previousblockhash;
assert(tip);
p('Previous TIP is now orphan. Back to:' + tip);
info('Previous TIP is now orphan. Back to:' + tip);
ret = true;
}
return ret;
},
function(err) {
self.startBlock = tip;
p('Resuming sync from block:'+tip);
info('Resuming sync from block:'+tip);
return next(err);
}
);
@ -275,7 +253,7 @@ HistoricSync.prototype.prepareFileSync = function(opts, next) {
try {
self.blockExtractor = new BlockExtractor(config.bitcoind.dataDir, config.network);
} catch (e) {
p(e.message + '. Disabling file sync.');
info(e.message + '. Disabling file sync.');
return next();
}
@ -288,7 +266,7 @@ HistoricSync.prototype.prepareFileSync = function(opts, next) {
var h = self.genesis;
p('Seeking file to:' + self.startBlock);
info('Seeking file to:' + self.startBlock);
//forward till startBlock
async.whilst(
function() {
@ -312,26 +290,26 @@ HistoricSync.prototype.prepareRpcSync = function(opts, next) {
if (self.blockExtractor) return next();
self.getFn = self.getBlockFromRPC;
self.allowReorgs = true;
self.currentRpcHash = self.startBlock;
self.allowReorgs = false;
return next();
};
HistoricSync.prototype.showSyncStartMessage = function() {
var self = this;
p('Got ' + self.connectedCountDB +
info('Got ' + self.connectedCountDB +
' blocks in current DB, out of ' + self.blockChainHeight + ' block at bitcoind');
if (self.blockExtractor) {
p('bitcoind dataDir configured...importing blocks from .dat files');
p('First file index: ' + self.blockExtractor.currentFileIndex);
info('bitcoind dataDir configured...importing blocks from .dat files');
info('First file index: ' + self.blockExtractor.currentFileIndex);
}
else {
p('syncing from RPC (slow)');
info('syncing from RPC (slow)');
}
p('Starting from: ', self.startBlock);
info('Starting from: ', self.startBlock);
self.showProgress();
};
@ -389,7 +367,7 @@ HistoricSync.prototype.start = function(opts, next) {
var self = this;
if (self.status==='starting' || self.status==='syncing') {
p('## Wont start to sync while status is %s', self.status);
error('## Wont start to sync while status is %s', self.status);
return next();
}
@ -404,17 +382,14 @@ HistoricSync.prototype.start = function(opts, next) {
function (w_cb) {
self.getFn(function(err,blockInfo) {
if (err) return w_cb(self.setError(err));
if (blockInfo && blockInfo.hash) {
if (blockInfo && blockInfo.hash
&& (!opts.stopAt || opts.stopAt !== blockInfo.hash)
) {
self.syncedBlocks++;
self.sync.storeTipBlock(blockInfo, self.allowReorgs, function(err) {
if (err) return w_cb(self.setError(err));
self.sync.bDb.setTip(blockInfo.hash, function(err) {
if (err) return w_cb(self.setError(err));
setImmediate(function(){
return w_cb(err);
});
setImmediate(function(){
return w_cb(err);
});
});
}

View File

@ -49,10 +49,8 @@ PeerSync.prototype.handleInv = function(info) {
PeerSync.prototype.handleTx = function(info) {
var self =this;
var tx = info.message.tx.getStandardizedObject();
tx.outs = info.message.tx.outs;
tx.ins = info.message.tx.ins;
console.log('[p2p_sync] Handle tx: ' + tx.hash);
var tx = this.sync.txDb.getStandardizedTx(info.message.tx);
console.log('[p2p_sync] Handle tx: ' + tx.txid);
tx.time = tx.time || Math.round(new Date().getTime() / 1000);
this.sync.storeTxs([tx], function(err) {
@ -62,10 +60,10 @@ PeerSync.prototype.handleTx = function(info) {
else {
if (self.shouldBroadcast) {
sockets.broadcastTx(tx);
if (tx.addrsToEmit) {
tx.addrsToEmit.forEach(function(a) {
sockets.broadcastAddressTx(a, tx.txid);
});
if (tx.relatedAddrs) {
for(var ii in tx.relatedAddrs){
sockets.broadcastAddressTx(tx.relatedAddrs[ii], tx.txid);
}
}
}
}
@ -77,7 +75,6 @@ PeerSync.prototype.handleBlock = function(info) {
var self = this;
var block = info.message.block;
var blockHash = bitcoreUtil.formatHashFull(block.calcHash());
console.log('[p2p_sync] Handle block: %s (allowReorgs: %s)', blockHash, self.allowReorgs);
var tx_hashes = block.txs.map(function(tx) {

View File

@ -7,6 +7,12 @@ var bitcore = require('bitcore');
var networks = bitcore.networks;
var async = require('async');
var logger = require('./logger').logger;
var d = logger.log;
var info = logger.info;
var syncId = 0;
function Sync(opts) {
@ -15,6 +21,7 @@ function Sync(opts) {
this.bDb = require('./BlockDb').default();
this.txDb = require('./TransactionDb').default();
this.network = config.network === 'testnet' ? networks.testnet : networks.livenet;
this.cachedLastHash = null;
}
Sync.prototype.close = function(cb) {
@ -56,7 +63,8 @@ Sync.prototype.destroy = function(next) {
* \
* F-G-NEW
* 1) Set F-G as connected (mark TXs as valid)
* 2) Declare D-E orphans (and possible invalidate TXs on them)
* 2) Set new heights in F-G-NEW
* 3) Declare D-E orphans (and possible invalidate TXs on them)
*
*
* Case 3)
@ -77,39 +85,40 @@ Sync.prototype.storeTipBlock = function(b, allowReorgs, cb) {
if (!b) return cb();
var self = this;
var oldTip, oldNext, needReorg = false;
var oldTip, oldNext, oldHeight, needReorg = false, height = -1;
var newPrev = b.previousblockhash;
async.series([
function(c) {
// TODO? remove this check?
self.bDb.has(b.hash, function(err, val) {
return c(err ||
(val ? new Error('WARN: Ignoring already existing block:' + b.hash) : null));
});
},
function(c) {
if (!allowReorgs) return c();
if (!allowReorgs || newPrev === self.cachedLastHash) return c();
self.bDb.has(newPrev, function(err, val) {
// Genesis? no problem
if (!val && newPrev.match(/^0+$/)) return c();
return c(err ||
(!val ? new Error('NEED_SYNC Ignoring block with non existing prev:' + b.hash) : null));
});
},
function(c) {
self.txDb.createFromBlock(b, function(err) {
return c(err);
});
},
function(c) {
if (!allowReorgs) return c();
self.bDb.getTip(function(err, val) {
oldTip = val;
if (oldTip && newPrev !== oldTip) needReorg = true;
self.bDb.getTip(function(err, hash, h) {
oldTip = hash;
oldHeight = hash ? (h || 0) : -1
if (oldTip && newPrev !== oldTip) {
needReorg = true;
console.log('## REORG Triggered, tip mismatch');
}
return c();
});
},
function(c) {
if (!needReorg) return c();
self.bDb.getNext(newPrev, function(err, val) {
@ -118,17 +127,29 @@ Sync.prototype.storeTipBlock = function(b, allowReorgs, cb) {
return c();
});
},
function(c) {
self.bDb.add(b, c);
function(c) {
if (!allowReorgs) return c();
if (needReorg) {
info('NEW TIP: %s NEED REORG (old tip: %s #%d)', b.hash, oldTip, oldHeight);
self.processReorg(oldTip, oldNext, newPrev, oldHeight, function(err, h) {
if (err) throw err;
height = h;
return c();
});
}
else {
height = oldHeight + 1;
return c();
}
},
function(c) {
if (!needReorg) return c();
console.log('NEW TIP: %s NEED REORG (old tip: %s)', b.hash, oldTip);
self.processReorg(oldTip, oldNext, newPrev, c);
self.cachedLastHash = b.hash; // just for speed up.
self.bDb.add(b, height, c);
},
function(c) {
if (!allowReorgs) return c();
self.bDb.setTip(b.hash, function(err) {
self.bDb.setTip(b.hash, height, function(err) {
return c(err);
});
},
@ -147,21 +168,20 @@ Sync.prototype.storeTipBlock = function(b, allowReorgs, cb) {
});
};
Sync.prototype.processReorg = function(oldTip, oldNext, newPrev, cb) {
Sync.prototype.processReorg = function(oldTip, oldNext, newPrev, oldHeight, cb) {
var self = this;
var orphanizeFrom;
var orphanizeFrom, newHeight;
async.series([
function(c) {
self.bDb.isMain(newPrev, function(err, val) {
if (!val) return c();
self.bDb.getHeight(newPrev, function(err, height) {
if (!height) return c(new Error('Could not found block:' + newPrev));
if (height<0) return c();
console.log('# Reorg Case 1)');
// case 1
newHeight = height + 1;
info('# Reorg Case 1) OldNext: %s NewHeight: %d', oldNext, newHeight);
orphanizeFrom = oldNext;
return c(err);
});
@ -169,10 +189,12 @@ Sync.prototype.processReorg = function(oldTip, oldNext, newPrev, cb) {
function(c) {
if (orphanizeFrom) return c();
console.log('# Reorg Case 2)');
self.setBranchConnectedBackwards(newPrev, function(err, yHash, newYHashNext) {
info('# Reorg Case 2)');
self.setBranchConnectedBackwards(newPrev, function(err, yHash, newYHashNext, height) {
if (err) return c(err);
newHeight = height;
self.bDb.getNext(yHash, function(err, yHashNext) {
// Connect the new branch, and orphanize the old one.
orphanizeFrom = yHashNext;
self.bDb.setNext(yHash, newYHashNext, function(err) {
return c(err);
@ -182,25 +204,17 @@ Sync.prototype.processReorg = function(oldTip, oldNext, newPrev, cb) {
},
function(c) {
if (!orphanizeFrom) return c();
self.setBranchOrphan(orphanizeFrom, function(err) {
self._setBranchOrphan(orphanizeFrom, function(err) {
return c(err);
});
},
],
function(err) {
return cb(err);
return cb(err, newHeight);
});
};
Sync.prototype.setBlockMain = function(hash, isMain, cb) {
var self = this;
self.bDb.setMain(hash, isMain, function(err) {
if (err) return cb(err);
return self.txDb.handleBlockChange(hash, isMain, cb);
});
};
Sync.prototype.setBranchOrphan = function(fromHash, cb) {
Sync.prototype._setBranchOrphan = function(fromHash, cb) {
var self = this,
hashInterator = fromHash;
@ -209,7 +223,7 @@ Sync.prototype.setBranchOrphan = function(fromHash, cb) {
return hashInterator;
},
function(c) {
self.setBlockMain(hashInterator, false, function(err) {
self.bDb.setBlockNotMain(hashInterator, function(err) {
if (err) return cb(err);
self.bDb.getNext(hashInterator, function(err, val) {
hashInterator = val;
@ -220,43 +234,52 @@ Sync.prototype.setBranchOrphan = function(fromHash, cb) {
};
Sync.prototype.setBranchConnectedBackwards = function(fromHash, cb) {
//console.log('[Sync.js.219:setBranchConnectedBackwards:]',fromHash); //TODO
var self = this,
hashInterator = fromHash,
lastHash = fromHash,
isMain;
yHeight,
branch = [];
async.doWhilst(
function(c) {
self.setBlockMain(hashInterator, true, function(err) {
branch.unshift(hashInterator);
self.bDb.getPrev(hashInterator, function(err, val) {
if (err) return c(err);
self.bDb.getPrev(hashInterator, function(err, val) {
if (err) return c(err);
lastHash = hashInterator;
hashInterator = val;
self.bDb.isMain(hashInterator, function(err, val) {
isMain = val;
return c();
});
lastHash = hashInterator;
hashInterator = val;
self.bDb.getHeight(hashInterator, function(err, height) {
yHeight = height;
return c();
});
});
},
function() {
return hashInterator && !isMain;
return hashInterator && yHeight<=0;
},
function(err) {
console.log('\tFound yBlock:', hashInterator);
return cb(err, hashInterator, lastHash);
}
);
function() {
info('\tFound yBlock: %s #%d', hashInterator, yHeight);
var heightIter = yHeight + 1;
var hashIter;
async.whilst(
function() {
hashIter = branch.shift();
return hashIter;
},
function(c) {
self.bDb.setBlockMain(hashIter, heightIter++, c);
},
function(err) {
return cb(err, hashInterator, lastHash, heightIter);
});
});
};
//Store unconfirmed TXs
Sync.prototype.storeTxs = function(txs, cb) {
var self = this;
self.txDb.createFromArray(txs, null, function(err) {
if (err) return cb(err);
return cb(err);
});
this.txDb.addMany(txs, cb);
};

View File

@ -2,11 +2,6 @@
var imports = require('soop').imports();
// blockHash -> txid mapping
var IN_BLK_PREFIX = 'txb-'; //txb-<txid>-<block> => 1/0 (connected or not)
// Only for orphan blocks
var FROM_BLK_PREFIX = 'tx-'; //tx-<block>-<txid> => 1
// to show tx outs
var OUTS_PREFIX = 'txo-'; //txo-<txid>-<n> => [addr, btc_sat]
@ -18,6 +13,7 @@ var ADDR_PREFIX = 'txa-'; //txa-<addr>-<txid>-<n> => + btc_sat:ts [:<txid>-<n>](
// TODO: use bitcore networks module
var genesisTXID = '4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b';
var CONCURRENCY = 10;
var DEFAULT_SAFE_CONFIRMATIONS = 6;
var MAX_OPEN_FILES = 500;
// var CONFIRMATION_NR_TO_NOT_CHECK = 10; //Spend
@ -32,25 +28,36 @@ var bitcore = require('bitcore'),
levelup = require('levelup'),
async = require('async'),
config = require('../config/config'),
assert = require('assert');
assert = require('assert'),
Script = bitcore.Script,
bitcoreUtil = bitcore.util,
buffertools = require('buffertools');
var logger = require('./logger').logger;
var info = logger.info;
var db = imports.db || levelup(config.leveldb + '/txs',{maxOpenFiles: MAX_OPEN_FILES} );
var Script = bitcore.Script;
// This is 0.1.2 = > c++ version of base57-native
var base58 = require('base58-native').base58Check;
var encodedData = require('soop').load('bitcore/util/EncodedData',{
base58: base58
});
var versionedData= require('soop').load('bitcore/util/VersionedData',{
parent: encodedData
});
var PoolMatch = imports.poolMatch || require('soop').load('./PoolMatch',config);
// This is 0.1.2 = > c++ version of base58-native
var base58 = require('base58-native').base58Check;
var encodedData = require('soop').load('bitcore/util/EncodedData',{
base58: base58
});
var versionedData= require('soop').load('bitcore/util/VersionedData',{
parent: encodedData
});
var Address = require('soop').load('bitcore/lib/Address',{
parent: versionedData
});
var TransactionDb = function() {
TransactionDb.super(this, arguments);
this.network = config.network === 'testnet' ? networks.testnet : networks.livenet;
this.poolMatch = new PoolMatch();
this.safeConfirmations = config.safeConfirmations || DEFAULT_SAFE_CONFIRMATIONS;
};
TransactionDb.prototype.close = function(cb) {
@ -67,25 +74,6 @@ TransactionDb.prototype.drop = function(cb) {
});
};
TransactionDb.prototype.has = function(txid, cb) {
var k = OUTS_PREFIX + txid;
db.get(k, function(err, val) {
var ret;
if (err && err.notFound) {
err = null;
ret = false;
}
if (typeof val !== undefined) {
ret = true;
}
return cb(err, ret);
});
};
TransactionDb.prototype._addSpentInfo = function(r, txid, index, ts) {
if (r.spentTxId) {
if (!r.multipleSpentAttempts) {
@ -181,25 +169,24 @@ TransactionDb.prototype._fillSpent = function(info, cb) {
};
TransactionDb.prototype._fillOutpoints = function(info, cb) {
TransactionDb.prototype._fillOutpoints = function(txInfo, cb) {
var self = this;
if (!info || info.isCoinBase) return cb();
if (!txInfo || txInfo.isCoinBase) return cb();
var valueIn = 0;
var incompleteInputs = 0;
async.eachLimit(info.vin, CONCURRENCY, function(i, c_in) {
self.fromTxIdN(i.txid, i.vout, info.confirmations, function(err, ret) {
//console.log('[TransactionDb.js.154:ret:]',ret); //TODO
async.eachLimit(txInfo.vin, CONCURRENCY, function(i, c_in) {
self.fromTxIdN(i.txid, i.vout, txInfo.confirmations, function(err, ret) {
if (!ret || !ret.addr || !ret.valueSat) {
console.log('Could not get TXouts in %s,%d from %s ', i.txid, i.vout, info.txid);
info('Could not get TXouts in %s,%d from %s ', i.txid, i.vout, txInfo.txid);
if (ret) i.unconfirmedInput = ret.unconfirmedInput;
incompleteInputs = 1;
return c_in(); // error not scalated
}
info.firstSeenTs = ret.spentTs;
txInfo.firstSeenTs = ret.spentTs;
i.unconfirmedInput = i.unconfirmedInput;
i.addr = ret.addr;
i.valueSat = ret.valueSat;
@ -210,18 +197,18 @@ TransactionDb.prototype._fillOutpoints = function(info, cb) {
* If confirmed by bitcoind, we could not check for double spents
* but we prefer to keep the flag of double spent attempt
*
if (info.confirmations
&& info.confirmations >= CONFIRMATION_NR_TO_NOT_CHECK)
if (txInfo.confirmations
&& txInfo.confirmations >= CONFIRMATION_NR_TO_NOT_CHECK)
return c_in();
isspent
*/
// Double spent?
if (ret.multipleSpentAttempt || !ret.spentTxId ||
(ret.spentTxId && ret.spentTxId !== info.txid)
(ret.spentTxId && ret.spentTxId !== txInfo.txid)
) {
if (ret.multipleSpentAttempts) {
ret.multipleSpentAttempts.forEach(function(mul) {
if (mul.spentTxId !== info.txid) {
if (mul.spentTxId !== txInfo.txid) {
i.doubleSpentTxID = ret.spentTxId;
i.doubleSpentIndex = ret.spentIndex;
}
@ -240,10 +227,10 @@ isspent
},
function() {
if (!incompleteInputs) {
info.valueIn = valueIn / util.COIN;
info.fees = (valueIn - (info.valueOut * util.COIN)).toFixed(0) / util.COIN;
txInfo.valueIn = valueIn / util.COIN;
txInfo.fees = (valueIn - (txInfo.valueOut * util.COIN)).toFixed(0) / util.COIN;
} else {
info.incompleteInputs = 1;
txInfo.incompleteInputs = 1;
}
return cb();
});
@ -252,12 +239,11 @@ isspent
TransactionDb.prototype._getInfo = function(txid, next) {
var self = this;
Rpc.getTxInfo(txid, function(err, info) {
Rpc.getTxInfo(txid, function(err, txInfo) {
if (err) return next(err);
self._fillOutpoints(info, function() {
self._fillSpent(info, function() {
return next(null, info);
self._fillOutpoints(txInfo, function() {
self._fillSpent(txInfo, function() {
return next(null, txInfo);
});
});
});
@ -306,7 +292,7 @@ TransactionDb.prototype.fromTxIdN = function(txid, n, confirmations, cb) {
/*
* If this TxID comes from an RPC request
* the .confirmations value from bitcoind is available
* so we could avoid checking if the input were double spented
* so we could avoid checking if the input was double spent
*
* This speed up address calculations by ~30%
*
@ -334,42 +320,133 @@ TransactionDb.prototype.fromTxIdN = function(txid, n, confirmations, cb) {
});
};
TransactionDb.prototype.fillConfirmations = function(o, cb) {
TransactionDb.prototype.deleteCacheForAddress = function(addr,cb) {
var k = ADDR_PREFIX + addr + '-';
var dbScript = [];
db.createReadStream({
start: k,
end: k + '~'
})
.on('data', function(data) {
var v = data.value.split(':');
dbScript.push({
type: 'put',
key: data.key,
value: v.slice(0,2).join(':'),
});
})
.on('error', function(err) {
return cb(err);
})
.on('end', function (){
db.batch(dbScript,cb);
});
};
TransactionDb.prototype.cacheConfirmations = function(txouts,cb) {
var self = this;
self.isConfirmed(o.txid, function(err, is) {
if (err) return cb(err);
var dbScript=[];
for(var ii in txouts){
var txout=txouts[ii];
o.isConfirmed = is;
if (!o.spentTxId) return cb();
//everything already cached?
if (txout.spentIsConfirmedCached) {
continue;
}
if (o.multipleSpentAttempts) {
var infoToCache = [];
if (txout.confirmations > self.safeConfirmations) {
if (!txout.isConfirmedCached) infoToCache.push(1);
async.eachLimit(o.multipleSpentAttempts, CONCURRENCY,
function(oi, e_c) {
self.isConfirmed(oi.spentTxId, function(err, is) {
if (err) return;
if (is) {
o.spentTxId = oi.spentTxId;
o.index = oi.index;
o.spentIsConfirmed = 1;
}
return e_c();
});
}, cb);
} else {
self.isConfirmed(o.spentTxId, function(err, is) {
if (err) return cb(err);
o.spentIsConfirmed = is;
return cb();
if (txout.spentConfirmations > self.safeConfirmations) {
// console.log('[TransactionDb.js.309]',txout); //TODO
infoToCache = infoToCache.concat([1, txout.spentTxId, txout.spentIndex, txout.spentTs]);
}
if (infoToCache.length){
// if spent, we overwrite scriptPubKey cache (not needed anymore)
// Last 1 = txout.isConfirmedCached (must be equal to 1 at this point)
infoToCache.unshift(txout.value_sat,txout.ts, 1);
dbScript.push({
type: 'put',
key: txout.key,
value: infoToCache.join(':'),
});
}
}
}
//console.log('[TransactionDb.js.339:dbScript:]',dbScript); //TODO
db.batch(dbScript,cb);
};
TransactionDb.prototype.cacheScriptPubKey = function(txouts,cb) {
var self = this;
var dbScript=[];
for(var ii in txouts){
var txout=txouts[ii];
//everything already cached?
if (txout.scriptPubKeyCached || txout.spentTxId) {
continue;
}
if (txout.scriptPubKey) {
var infoToCache = [txout.value_sat,txout.ts, txout.isConfirmedCached?1:0, txout.scriptPubKey];
dbScript.push({
type: 'put',
key: txout.key,
value: infoToCache.join(':'),
});
}
});
}
db.batch(dbScript,cb);
};
TransactionDb.prototype._parseAddrData = function(data) {
var k = data.key.split('-');
var v = data.value.split(':');
var item = {
key: data.key,
txid: k[2],
index: parseInt(k[3]),
value_sat: parseInt(v[0]),
ts: parseInt(v[1]),
};
// Cache
if (v[2]){
item.isConfirmed = 1;
item.isConfirmedCached = 1;
//console.log('[TransactionDb.js.356] CACHE HIT CONF:', item.key); //TODO
// Sent, confirmed
if (v[3] === 1){
//console.log('[TransactionDb.js.356] CACHE HIT SPENT:', item.key); //TODO
item.spentIsConfirmed = 1;
item.spentIsConfirmedCached = 1;
item.spentTxId = v[4];
item.spentIndex = parseInt(v[5]);
item.spentTs = parseInt(v[6]);
}
// Scriptpubkey cached
else if (v[3]) {
item.scriptPubKey = v[3];
item.scriptPubKeyCached = 1;
}
}
return item;
};
TransactionDb.prototype.fromAddr = function(addr, cb) {
var self = this;
var k = ADDR_PREFIX + addr + '-';
var ret = [];
@ -378,21 +455,11 @@ TransactionDb.prototype.fromAddr = function(addr, cb) {
end: k + '~'
})
.on('data', function(data) {
var k = data.key.split('-');
var v = data.value.split(':');
ret.push({
txid: k[2],
index: parseInt(k[3]),
value_sat: parseInt(v[0]),
ts: parseInt(v[1]),
});
})
.on('error', function(err) {
return cb(err);
ret.push(self._parseAddrData(data));
})
.on('error', cb)
.on('end', function() {
async.eachLimit(ret, CONCURRENCY, function(o, e_c) {
async.eachLimit(ret.filter(function(x){return !x.spentIsConfirmed;}), CONCURRENCY, function(o, e_c) {
var k = SPENT_PREFIX + o.txid + '-' + o.index + '-';
db.createReadStream({
start: k,
@ -402,28 +469,75 @@ TransactionDb.prototype.fromAddr = function(addr, cb) {
var k = data.key.split('-');
self._addSpentInfo(o, k[3], k[4], data.value);
})
.on('error', function(err) {
return e_c(err);
})
.on('end', function(err) {
return e_c(err);
});
.on('error', e_c)
.on('end', e_c);
},
function() {
async.eachLimit(ret, CONCURRENCY, function(o, e_c) {
self.fillConfirmations(o, e_c);
}, function(err) {
return cb(err, ret);
});
function(err) {
return cb(err, ret);
});
});
};
TransactionDb.prototype._fromBuffer = function (buf) {
var buf2 = buffertools.reverse(buf);
return parseInt(buf2.toString('hex'), 16);
};
TransactionDb.prototype.getStandardizedTx = function (tx, time, isCoinBase) {
var self = this;
tx.txid = bitcoreUtil.formatHashFull(tx.getHash());
var ti=0;
tx.vin = tx.ins.map(function(txin) {
var ret = {n: ti++};
if (isCoinBase) {
ret.isCoinBase = true;
} else {
ret.txid = buffertools.reverse(new Buffer(txin.getOutpointHash())).toString('hex');
ret.vout = txin.getOutpointIndex();
}
return ret;
});
var to = 0;
tx.vout = tx.outs.map(function(txout) {
var val;
if (txout.s) {
var s = new Script(txout.s);
var addrs = new Address.fromScriptPubKey(s, config.network);
// support only for p2pubkey p2pubkeyhash and p2sh
if (addrs && addrs.length === 1) {
val = {addresses: [addrs[0].toString() ] };
}
}
return {
valueSat: self._fromBuffer(txout.v),
scriptPubKey: val,
n: to++,
};
});
tx.time = time;
return tx;
};
TransactionDb.prototype.fillScriptPubKey = function(txouts, cb) {
var self=this;
// Complete utxo info
async.eachLimit(txouts, CONCURRENCY, function (txout, a_c) {
self.fromIdInfoSimple(txout.txid, function(err, info) {
if (!info || !info.vout) return a_c(err);
txout.scriptPubKey = info.vout[txout.index].scriptPubKey.hex;
return a_c();
});
}, function(){
self.cacheScriptPubKey(txouts, cb);
});
};
TransactionDb.prototype.removeFromTxId = function(txid, cb) {
async.series([
function(c) {
db.createReadStream({
start: OUTS_PREFIX + txid + '-',
@ -452,229 +566,109 @@ TransactionDb.prototype.removeFromTxId = function(txid, cb) {
};
TransactionDb.prototype.adaptTxObject = function(txInfo) {
var self = this;
// adapt bitcore TX object to bitcoind JSON response
txInfo.txid = txInfo.hash;
var to = 0;
var tx = txInfo;
if (tx.outs) {
tx.outs.forEach(function(o) {
var s = new Script(o.s);
var addrs = new Address.fromScriptPubKey(s, config.network);
// support only for p2pubkey p2pubkeyhash and p2sh
if (addrs.length === 1) {
tx.out[to].addrStr = addrs[0].toString();
tx.out[to].n = to;
}
to++;
});
TransactionDb.prototype._addScript = function(tx) {
var relatedAddrs = [];
var dbScript = [];
var ts = tx.time;
var txid = tx.txid || tx.hash;
// var u=require('util');
// console.log('[TransactionDb.js.518]', u.inspect(tx,{depth:10})); //TODO
// Input Outpoints (mark them as spent)
for(var ii in tx.vin) {
var i = tx.vin[ii];
if (i.txid){
var k = SPENT_PREFIX + i.txid + '-' + i.vout + '-' + txid + '-' + i.n;
dbScript.push({
type: 'put',
key: k,
value: ts || 0,
});
}
}
var count = 0;
txInfo.vin = txInfo. in .map(function(txin) {
var i = {};
for(var ii in tx.vout) {
var o = tx.vout[ii];
if ( o.scriptPubKey && o.scriptPubKey.addresses &&
o.scriptPubKey.addresses[0] && !o.scriptPubKey.addresses[1] // TODO : not supported=> standard multisig
) {
var addr = o.scriptPubKey.addresses[0];
var sat = o.valueSat || ((o.value||0) * util.COIN).toFixed(0);
if (txin.coinbase) {
txInfo.isCoinBase = true;
} else {
i.txid = txin.prev_out.hash;
i.vout = txin.prev_out.n;
}
i.n = count++;
return i;
});
count = 0;
txInfo.vout = txInfo.out.map(function(txout) {
var o = {};
o.value = txout.value;
o.n = count++;
if (txout.addrStr) {
o.scriptPubKey = {};
o.scriptPubKey.addresses = [txout.addrStr];
}
return o;
});
relatedAddrs[addr]=1;
var k = OUTS_PREFIX + txid + '-' + o.n;
dbScript.push({
type: 'put',
key: k,
value: addr + ':' + sat,
},{
type: 'put',
key: ADDR_PREFIX + addr + '-' + txid + '-' + o.n,
value: sat + ':' + ts,
});
}
}
tx.relatedAddrs=relatedAddrs;
return dbScript;
};
TransactionDb.prototype.add = function(tx, blockhash, cb) {
var dbScript = this._addScript(tx, blockhash);
db.batch(dbScript, cb);
};
TransactionDb.prototype._addManyFromObjs = function(txs, next) {
var dbScript = [];
for(var ii in txs){
var s = this._addScript(txs[ii]);
dbScript = dbScript.concat(s);
}
db.batch(dbScript, next);
};
TransactionDb.prototype._addManyFromHashes = function(txs, next) {
var self=this;
var dbScript = [];
async.eachLimit(txs, CONCURRENCY, function(tx, each_cb) {
if (tx === genesisTXID)
return each_cb();
Rpc.getTxInfo(tx, function(err, inInfo) {
if (!inInfo) return each_cb(err);
dbScript = dbScript.concat(self._addScript(inInfo));
return each_cb();
});
},
function(err) {
if (err) return next(err);
db.batch(dbScript,next);
});
};
TransactionDb.prototype.addMany = function(txs, next) {
if (!txs) return next();
var fn = (typeof txs[0] ==='string') ?
this._addManyFromHashes : this._addManyFromObjs;
return fn.apply(this,[txs, next]);
};
TransactionDb.prototype.getPoolInfo = function(txid, cb) {
var self = this;
var addrs = [];
if (tx.hash) self.adaptTxObject(tx);
Rpc.getTxInfo(txid, function(err, txInfo) {
if (err) return cb(false);
var ret;
var ts = tx.time;
async.series([
// Input Outpoints (mark them as spent)
function(p_c) {
if (tx.isCoinBase) return p_c();
async.forEachLimit(tx.vin, CONCURRENCY,
function(i, next_out) {
db.batch()
.put(SPENT_PREFIX + i.txid + '-' + i.vout + '-' + tx.txid + '-' + i.n,
ts || 0)
.write(next_out);
},
function(err) {
return p_c(err);
});
},
// Parse Outputs
function(p_c) {
async.forEachLimit(tx.vout, CONCURRENCY,
function(o, next_out) {
if (o.value && o.scriptPubKey &&
o.scriptPubKey.addresses &&
o.scriptPubKey.addresses[0] && !o.scriptPubKey.addresses[1] // TODO : not supported
) {
var addr = o.scriptPubKey.addresses[0];
var sat = Math.round(o.value * util.COIN);
if (addrs.indexOf(addr) === -1) {
addrs.push(addr);
}
// existed?
var k = OUTS_PREFIX + tx.txid + '-' + o.n;
db.get(k, function(err, val) {
if (!val || (err && err.notFound)) {
db.batch()
.put(k, addr + ':' + sat)
.put(ADDR_PREFIX + addr + '-' + tx.txid + '-' + o.n, sat + ':' + ts)
.write(next_out);
} else {
return next_out();
}
});
} else {
return next_out();
}
},
function(err) {
if (err) {
console.log('ERR at TX %s: %s', tx.txid, err);
return cb(err);
}
return p_c();
});
},
function(p_c) {
if (!blockhash) {
return p_c();
}
return self.setConfirmation(tx.txid, blockhash, true, p_c);
},
], function(err) {
if (addrs.length > 0 && !blockhash) {
// only emit if we are processing a single tx (not from a block)
tx.addrsToEmit=addrs;
}
return cb(err);
if (txInfo && txInfo.isCoinBase)
ret = self.poolMatch.match(new Buffer(txInfo.vin[0].coinbase, 'hex'));
return cb(ret);
});
};
TransactionDb.prototype.setConfirmation = function(txId, blockHash, confirmed, c) {
if (!blockHash) return c();
confirmed = confirmed ? 1 : 0;
db.batch()
.put(IN_BLK_PREFIX + txId + '-' + blockHash, confirmed)
.put(FROM_BLK_PREFIX + blockHash + '-' + txId, 1)
.write(c);
};
// This slowdown addr balance calculation by 100%
TransactionDb.prototype.isConfirmed = function(txId, c) {
var k = IN_BLK_PREFIX + txId;
var ret = false;
db.createReadStream({
start: k,
end: k + '~'
})
.on('data', function(data) {
if (data.value === '1') ret = true;
})
.on('error', function(err) {
return c(err);
})
.on('end', function(err) {
return c(err, ret);
});
};
TransactionDb.prototype.handleBlockChange = function(hash, isMain, cb) {
var toChange = [];
console.log('\tSearching Txs from block:' + hash);
var k = FROM_BLK_PREFIX + hash;
var k2 = IN_BLK_PREFIX;
// This is slow, but prevent us to create a new block->tx index.
db.createReadStream({
start: k,
end: k + '~'
})
.on('data', function(data) {
var ks = data.key.split('-');
toChange.push({
key: k2 + ks[2] + '-' + ks[1],
type: 'put',
value: isMain ? 1 : 0,
});
})
.on('error', function(err) {
return cb(err);
})
.on('end', function(err) {
if (err) return cb(err);
console.log('\t%s %d Txs', isMain ? 'Confirming' : 'Invalidating', toChange.length);
db.batch(toChange, cb);
});
};
// txs can be a [hashes] or [txObjects]
TransactionDb.prototype.createFromArray = function(txs, blockHash, next) {
var self = this;
if (!txs) return next();
async.forEachLimit(txs, CONCURRENCY, function(t, each_cb) {
if (typeof t === 'string') {
// TODO: parse it from networks.genesisTX?
if (t === genesisTXID) return each_cb();
Rpc.getTxInfo(t, function(err, inInfo) {
if (!inInfo) return each_cb(err);
return self.add(inInfo, blockHash, each_cb);
});
} else {
return self.add(t, blockHash, each_cb);
}
},
function(err) {
return next(err);
});
};
TransactionDb.prototype.createFromBlock = function(b, next) {
var self = this;
if (!b || !b.tx) return next();
return self.createFromArray(b.tx, b.hash, next);
};
module.exports = require('soop')(TransactionDb);

5
lib/logger.js Normal file
View File

@ -0,0 +1,5 @@
var winston = require('winston');
winston.info('starting...')
module.exports.logger=winston;

View File

@ -1,7 +1,7 @@
{
"name": "insight-bitcore-api",
"description": "An open-source bitcoin blockchain API. The Insight API provides you with a convenient, powerful and simple way to query and broadcast data on the bitcoin network and build your own services with it.",
"version": "0.1.12",
"version": "0.2.1",
"author": {
"name": "Ryan X Charles",
"email": "ryan@bitpay.com"
@ -60,13 +60,13 @@
"soop": "=0.1.5",
"commander": "*",
"bignum": "*",
"winston": "*",
"express": "~3.4.7",
"buffertools": "*",
"should": "~2.1.1",
"socket.io": "~0.9.16",
"moment": "~2.5.0",
"sinon": "~1.7.3",
"chai": "~1.8.1",
"xmlhttprequest": "~1.6.0",
"bufferput": "git://github.com/bitpay/node-bufferput.git"
},
@ -80,6 +80,7 @@
"grunt-nodemon": "~0.2.0",
"grunt-mocha-test": "~0.8.1",
"should": "2.1.1",
"chai": "=1.9.1",
"grunt-markdown": "~0.5.0"
}
}

View File

@ -5,6 +5,7 @@ process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var should = require('chai');
var assert = require('assert'),
fs = require('fs'),
util = require('util'),
@ -29,10 +30,13 @@ describe('TransactionDb fromIdWithInfo', function(){
assert.equal(tx.txid, txid);
assert(!tx.info.isCoinBase);
for(var i=0; i<20; i++)
for(var i=0; i<20; i++) {
assert(parseFloat(tx.info.vin[i].value) === parseFloat(50), 'input '+i);
assert(tx.info.vin[0].addr === 'msGKGCy2i8wbKS5Fo1LbWUTJnf1GoFFG59', 'addr 0');
assert(tx.info.vin[1].addr === 'mfye7oHsdrHbydtj4coPXCasKad2eYSv5P', 'addr 1');
}
tx.info.vin[0].addr.should.equal('msGKGCy2i8wbKS5Fo1LbWUTJnf1GoFFG59');
tx.info.vin[1].addr.should.equal('mfye7oHsdrHbydtj4coPXCasKad2eYSv5P');
done();
});
});
@ -134,7 +138,7 @@ describe('TransactionDb Outs', function(){
assert.equal(readItems.length,0);
var unmatch=[];
txDb.createFromArray([v.txid], null, function(err) {
txDb.addMany([v.txid], function(err) {
if (err) return done(err);
txDb.fromTxId( v.txid, function(err, readItems) {

View File

@ -27,7 +27,7 @@ describe('TransactionDb Expenses', function(){
function(txid,c_out) {
async.each(spentValid[txid],
function(i,c_in) {
txDb.createFromArray([i.txid], null, function(err) {
txDb.addMany([i.txid], function(err) {
return c_in();
});
},

File diff suppressed because it is too large Load Diff

View File

@ -11,8 +11,11 @@ var assert = require('assert'),
addrValid = JSON.parse(fs.readFileSync('test/integration/addr.json')),
utxoValid = JSON.parse(fs.readFileSync('test/integration/utxo.json'));
var should = require('chai');
var txDb;
describe('Address balances', function() {
this.timeout(5000);
before(function(c) {
txDb = TransactionDb;
@ -24,18 +27,16 @@ describe('Address balances', function() {
console.log(v.addr + ' => disabled in JSON');
} else {
it('Address info for: ' + v.addr, function(done) {
this.timeout(5000);
var a = new Address(v.addr, txDb);
a.update(function(err) {
if (err) done(err);
assert.equal(v.addr, a.addrStr);
assert.equal(a.unconfirmedTxApperances ,v.unconfirmedTxApperances || 0, 'unconfirmedTxApperances');
assert.equal(a.unconfirmedBalanceSat ,v.unconfirmedBalanceSat || 0, 'unconfirmedBalanceSat: ' + a.unconfirmedBalanceSat + ' vs.: ' + v.unconfirmedBalanceSat );
v.addr.should.equal(a.addrStr);
a.unconfirmedTxApperances.should.equal(v.unconfirmedTxApperances || 0, 'unconfirmedTxApperances');
a.unconfirmedBalanceSat.should.equal(v.unconfirmedBalanceSat || 0, 'unconfirmedBalanceSat');
if (v.txApperances)
assert.equal(v.txApperances, a.txApperances, 'txApperances: ' + a.txApperances);
if (v.totalReceived) assert.equal(v.totalReceived, a.totalReceived, 'received: ' + a.totalReceived);
a.txApperances.should.equal(v.txApperances, 'txApperances');
if (v.totalReceived) a.totalReceived.should.equal(v.totalReceived,'totalReceived');
if (v.totalSent) assert.equal(v.totalSent, a.totalSent, 'send: ' + a.totalSent);
if (v.balance) assert.equal(v.balance, a.balance, 'balance: ' + a.balance);
@ -49,30 +50,137 @@ describe('Address balances', function() {
done();
});
});
it('Address info (cache) for: ' + v.addr, function(done) {
var a = new Address(v.addr, txDb);
a.update(function(err) {
if (err) done(err);
v.addr.should.equal(a.addrStr);
a.unconfirmedTxApperances.should.equal(v.unconfirmedTxApperances || 0, 'unconfirmedTxApperances');
a.unconfirmedBalanceSat.should.equal(v.unconfirmedBalanceSat || 0, 'unconfirmedBalanceSat');
if (v.txApperances)
a.txApperances.should.equal(v.txApperances, 'txApperances');
if (v.totalReceived) a.totalReceived.should.equal(v.totalReceived,'totalReceived');
if (v.totalSent) assert.equal(v.totalSent, a.totalSent, 'send: ' + a.totalSent);
if (v.balance) assert.equal(v.balance, a.balance, 'balance: ' + a.balance);
done();
},1);
});
}
});
});
describe('Address cache ', function() {
this.timeout(5000);
before(function(c) {
txDb = TransactionDb;
txDb.deleteCacheForAddress('muAt5RRqDarPFCe6qDXGZc54xJjXYUyepG',function(){
txDb.deleteCacheForAddress('mt2AzeCorSf7yFckj19HFiXJgh9aNyc4h3',c);
});
});
it('cache case 1 w/o cache', function(done) {
var a = new Address('muAt5RRqDarPFCe6qDXGZc54xJjXYUyepG', txDb);
a.update(function(err) {
if (err) done(err);
a.balance.should.equal(0, 'balance');
a.totalReceived.should.equal(19175, 'totalReceived');
a.txApperances.should.equal(2, 'txApperances');
return done();
});
});
it('cache case 1 w cache', function(done) {
var a = new Address('muAt5RRqDarPFCe6qDXGZc54xJjXYUyepG', txDb);
a.update(function(err) {
if (err) done(err);
a.balance.should.equal(0, 'balance');
a.totalReceived.should.equal(19175, 'totalReceived');
a.txApperances.should.equal(2, 'txApperances');
return done();
});
});
it('cache case 2 w/o cache', function(done) {
var a = new Address('mt2AzeCorSf7yFckj19HFiXJgh9aNyc4h3', txDb);
a.update(function(err) {
if (err) done(err);
a.balance.should.equal(0, 'balance');
a.totalReceived.should.equal(1376000, 'totalReceived');
a.txApperances.should.equal(8003, 'txApperances');
return done();
});
},1);
it('cache case 2 w cache', function(done) {
var a = new Address('mt2AzeCorSf7yFckj19HFiXJgh9aNyc4h3', txDb);
a.update(function(err) {
if (err) done(err);
a.balance.should.equal(0, 'balance');
a.totalReceived.should.equal(1376000, 'totalReceived');
a.txApperances.should.equal(8003, 'txApperances');
return done();
},1);
});
});
//tested against https://api.biteasy.com/testnet/v1/addresses/2N1pLkosf6o8Ciqs573iwwgVpuFS6NbNKx5/unspent-outputs?per_page=40
describe('Address utxo', function() {
before(function(c) {
txDb = TransactionDb;
var l = utxoValid.length;
var d=0;
utxoValid.forEach(function(v) {
//console.log('Deleting cache for', v.addr); //TODO
txDb.deleteCacheForAddress(v.addr,function(){
if (d++ == l-1) return c();
});
});
});
utxoValid.forEach(function(v) {
if (v.disabled) {
console.log(v.addr + ' => disabled in JSON');
} else {
it('Address utxo for: ' + v.addr, function(done) {
this.timeout(50000);
this.timeout(2000);
var a = new Address(v.addr, txDb);
a.getUtxo(function(err, utxo) {
if (err) done(err);
assert.equal(v.addr, a.addrStr);
if (v.length) assert.equal(v.length, utxo.length, 'length: ' + utxo.length);
if (v.tx0id) assert.equal(v.tx0id, utxo[0].txid, 'have tx: ' + utxo[0].txid);
if (v.tx0scriptPubKey)
assert.equal(v.tx0scriptPubKey, utxo[0].scriptPubKey, 'have tx: ' + utxo[0].scriptPubKey);
if (v.tx0amount)
assert.equal(v.tx0amount, utxo[0].amount, 'amount: ' + utxo[0].amount);
if (v.length) utxo.length.should.equal(v.length, 'Unspent count');
if (v.tx0id) {
var x=utxo.filter(function(x){
return x.txid === v.tx0id;
});
assert(x,'found output');
x.length.should.equal(1,'found output');
x[0].scriptPubKey.should.equal(v.tx0scriptPubKey,'scriptPubKey');
x[0].amount.should.equal(v.tx0amount,'amount');
}
done();
});
});
it('Address utxo (cached) for: ' + v.addr, function(done) {
this.timeout(2000);
var a = new Address(v.addr, txDb);
a.getUtxo(function(err, utxo) {
if (err) done(err);
assert.equal(v.addr, a.addrStr);
if (v.length) utxo.length.should.equal(v.length, 'Unspent count');
if (v.tx0id) {
var x=utxo.filter(function(x){
return x.txid === v.tx0id;
});
assert(x,'found output');
x.length.should.equal(1,'found output');
x[0].scriptPubKey.should.equal(v.tx0scriptPubKey,'scriptPubKey');
x[0].amount.should.equal(v.tx0amount,'amount');
}
done();
});
});

View File

@ -41,35 +41,36 @@
"totalReceived": 54.81284116
},
{
"disabled": 1,
"addr": "mzW2hdZN2um7WBvTDerdahKqRgj3md9C29",
"balance": 1271.87752288,
"totalReceived": 1271.87752288,
"balance": 1363.14677867,
"totalReceived": 1363.14677867,
"totalSent": 0,
"txApperances": 6197,
"unconfirmedTxApperances": 3,
"unconfirmedBalanceSat": 149174913
"txApperances": 7947,
"unconfirmedTxApperances": 5,
"unconfirmedBalanceSat": 149174913
},
{
"addr": "mjRmkmYzvZN3cA3aBKJgYJ65epn3WCG84H",
"txApperances": 7164,
"balance": 46413.0,
"txApperances": 7166,
"balance": 6513,
"totalReceived": 357130.17644359,
"totalSent": 310717.17644359
"totalSent": 350617.17644359
},
{
"addr": "mgKY35SXqxFpcKK3Dq9mW9919N7wYXvcFM",
"txApperances": 1,
"balance": 0.01979459,
"totalReceived": 0.01979459,
"txApperances": 2,
"balance": 0,
"totalReceived": 0.01979459,
"totalSent": 0,
"transactions": [ "91800d80bb4c69b238c9bfd94eb5155ab821e6b25cae5c79903d12853bbb4ed5" ]
},
{
"addr": "mmvP3mTe53qxHdPqXEvdu8WdC7GfQ2vmx5",
"balance": 10580.50027254,
"balance": 5524.61806422,
"totalReceived": 12157.65075053,
"totalSent": 1577.15047799,
"txApperances": 441,
"totalSent": 6633.03268631,
"txApperances": 443,
"transactions": [
"91800d80bb4c69b238c9bfd94eb5155ab821e6b25cae5c79903d12853bbb4ed5",
"f6e80d4fd1a2377406856c67d0cee5ac7e5120993ff97e617ca9aac33b4c6b1e",

View File

@ -7,10 +7,10 @@
"tx0amount": 0.38571339
},
{
"addr": "mgKY35SXqxFpcKK3Dq9mW9919N7wYXvcFM",
"length": 1,
"tx0id": "91800d80bb4c69b238c9bfd94eb5155ab821e6b25cae5c79903d12853bbb4ed5",
"tx0scriptPubKey": "76a91408cf4ceb2b7278043fcc7f545e6e6e73ef9a644f88ac",
"tx0amount": 0.01979459
}
"addr": "2N1pLkosf6o8Ciqs573iwwgVpuFS6NbNKx5",
"length": 13,
"tx0id": "b9cc61b55814a0f972788e9025db1013157f83716e08239026a156efe892a05c",
"tx0scriptPubKey": "a9145e0461e38796367580305e3615fc1b70e4c3307687",
"tx0amount": 0.001
}
]

View File

@ -15,6 +15,7 @@ program
.option('-D --destroy', 'Remove current DB (and start from there)', 0)
.option('-S --startfile', 'Number of file from bitcoind to start(default=0)')
.option('-R --rpc', 'Force sync with RPC')
.option('--stop [hash]', 'StopAt block',1)
.option('-v --verbose', 'Verbose 0/1', 0)
.parse(process.argv);
@ -30,10 +31,13 @@ async.series([
historicSync.sync.destroy(cb);
},
function(cb) {
historicSync.start({
var opts= {
forceStartFile: program.startfile,
forceRPC: program.rpc,
},cb);
stopAt: program.stop,
};
console.log('[options]',opts); //TODO
historicSync.start(opts,cb);
},
],
function(err) {