Merge pull request #85 from matiu/feature/optimizations
Feature/optimizations -- great jobs!
This commit is contained in:
commit
cb1861f10f
|
@ -5,9 +5,11 @@
|
||||||
*/
|
*/
|
||||||
var common = require('./common'),
|
var common = require('./common'),
|
||||||
async = require('async'),
|
async = require('async'),
|
||||||
BlockDb = require('../../lib/BlockDb');
|
BlockDb = require('../../lib/BlockDb'),
|
||||||
|
TransactionDb = require('../../lib/TransactionDb');
|
||||||
|
|
||||||
var bdb = new BlockDb();
|
var bdb = new BlockDb();
|
||||||
|
var tdb = new TransactionDb();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Find block by hash ...
|
* Find block by hash ...
|
||||||
|
@ -17,7 +19,7 @@ exports.block = function(req, res, next, hash) {
|
||||||
if (err || !block)
|
if (err || !block)
|
||||||
return common.handleErrors(err, res, next);
|
return common.handleErrors(err, res, next);
|
||||||
else {
|
else {
|
||||||
bdb.getPoolInfo(block.info.tx[0], function(info) {
|
tdb.getPoolInfo(block.info.tx[0], function(info) {
|
||||||
block.info.poolInfo = info;
|
block.info.poolInfo = info;
|
||||||
req.block = block.info;
|
req.block = block.info;
|
||||||
return next();
|
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;
|
block.info.poolInfo = info;
|
||||||
return cb(err, block.info);
|
return cb(err, block.info);
|
||||||
});
|
});
|
||||||
|
|
|
@ -32,10 +32,10 @@ module.exports.broadcastTx = function(tx) {
|
||||||
// Outputs
|
// Outputs
|
||||||
var valueOut = 0;
|
var valueOut = 0;
|
||||||
tx.vout.forEach(function(o) {
|
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);
|
ios.sockets.in('inv').emit('tx', t);
|
||||||
}
|
}
|
||||||
|
|
|
@ -9,6 +9,8 @@ var BitcoreUtil = bitcore.util;
|
||||||
var Parser = bitcore.BinaryParser;
|
var Parser = bitcore.BinaryParser;
|
||||||
var Buffer = bitcore.Buffer;
|
var Buffer = bitcore.Buffer;
|
||||||
var TransactionDb = imports.TransactionDb || require('../../lib/TransactionDb').default();
|
var TransactionDb = imports.TransactionDb || require('../../lib/TransactionDb').default();
|
||||||
|
var BlockDb = imports.BlockDb || require('../../lib/BlockDb').default();
|
||||||
|
var config = require('../../config/config');
|
||||||
var CONCURRENCY = 5;
|
var CONCURRENCY = 5;
|
||||||
|
|
||||||
function Address(addrStr) {
|
function Address(addrStr) {
|
||||||
|
@ -20,6 +22,7 @@ function Address(addrStr) {
|
||||||
|
|
||||||
this.txApperances = 0;
|
this.txApperances = 0;
|
||||||
this.unconfirmedTxApperances= 0;
|
this.unconfirmedTxApperances= 0;
|
||||||
|
this.seen = {};
|
||||||
|
|
||||||
// TODO store only txids? +index? +all?
|
// TODO store only txids? +index? +all?
|
||||||
this.transactions = [];
|
this.transactions = [];
|
||||||
|
@ -71,67 +74,44 @@ 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) {
|
Address.prototype.getUtxo = function(next) {
|
||||||
var self = this;
|
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 = [];
|
tDb.fromAddr(self.addrStr, function(err,txOut){
|
||||||
var db = TransactionDb;
|
|
||||||
|
|
||||||
db.fromAddr(self.addrStr, function(err,txOut){
|
|
||||||
if (err) return next(err);
|
if (err) return next(err);
|
||||||
|
var unspent = txOut.filter(function(x){
|
||||||
|
return !x.spentTxId;
|
||||||
|
});
|
||||||
|
|
||||||
// Complete utxo info
|
bDb.fillConfirmations(unspent, function() {
|
||||||
async.eachLimit(txOut,CONCURRENCY,function (txItem, a_c) {
|
tDb.fillScriptPubKey(unspent, function() {
|
||||||
db.fromIdInfoSimple(txItem.txid, function(err, info) {
|
ret = unspent.map(function(x){
|
||||||
if (!info || !info.hex) return a_c(err);
|
return {
|
||||||
|
|
||||||
var scriptPubKey = self._getScriptPubKey(info.hex, txItem.index);
|
|
||||||
|
|
||||||
// we are filtering out even unconfirmed spents!
|
|
||||||
// add || !txItem.spentIsConfirmed
|
|
||||||
if (!txItem.spentTxId) {
|
|
||||||
ret.push({
|
|
||||||
address: self.addrStr,
|
address: self.addrStr,
|
||||||
txid: txItem.txid,
|
txid: x.txid,
|
||||||
vout: txItem.index,
|
vout: x.index,
|
||||||
ts: txItem.ts,
|
ts: x.ts,
|
||||||
scriptPubKey: scriptPubKey,
|
scriptPubKey: x.scriptPubKey,
|
||||||
amount: txItem.value_sat / BitcoreUtil.COIN,
|
amount: x.value_sat / BitcoreUtil.COIN,
|
||||||
confirmations: txItem.isConfirmed ? info.confirmations : 0,
|
confirmations: x.isConfirmedCached ? (config.safeConfirmations+'+') : x.confirmations,
|
||||||
|
};
|
||||||
});
|
});
|
||||||
}
|
return next(null, ret);
|
||||||
return a_c(err);
|
|
||||||
});
|
});
|
||||||
}, function(err) {
|
|
||||||
return next(err,ret);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
Address.prototype.update = function(next, notxlist) {
|
|
||||||
var self = this;
|
|
||||||
if (!self.addrStr) return next();
|
|
||||||
|
|
||||||
var txs = [];
|
Address.prototype._addTxItem = function(txItem, notxlist) {
|
||||||
var db = TransactionDb;
|
|
||||||
async.series([
|
|
||||||
function (cb) {
|
|
||||||
var seen={};
|
|
||||||
db.fromAddr(self.addrStr, function(err,txOut){
|
|
||||||
if (err) return cb(err);
|
|
||||||
txOut.forEach(function(txItem){
|
|
||||||
var add=0, addSpend=0;
|
var add=0, addSpend=0;
|
||||||
var v = txItem.value_sat;
|
var v = txItem.value_sat;
|
||||||
|
var seen = this.seen;
|
||||||
|
var txs = [];
|
||||||
|
|
||||||
if ( !seen[txItem.txid] ) {
|
if ( !seen[txItem.txid] ) {
|
||||||
if (!notxlist) {
|
if (!notxlist) {
|
||||||
|
@ -148,37 +128,34 @@ Address.prototype.update = function(next, notxlist) {
|
||||||
seen[txItem.spentTxId]=1;
|
seen[txItem.spentTxId]=1;
|
||||||
addSpend=1;
|
addSpend=1;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (txItem.isConfirmed) {
|
if (txItem.isConfirmed) {
|
||||||
self.txApperances += add;
|
this.txApperances += add;
|
||||||
self.totalReceivedSat += v;
|
this.totalReceivedSat += v;
|
||||||
if (! txItem.spentTxId ) {
|
if (! txItem.spentTxId ) {
|
||||||
//unspent
|
//unspent
|
||||||
self.balanceSat += v;
|
this.balanceSat += v;
|
||||||
}
|
}
|
||||||
else if(!txItem.spentIsConfirmed) {
|
else if(!txItem.spentIsConfirmed) {
|
||||||
// unspent
|
// unspent
|
||||||
self.balanceSat += v;
|
this.balanceSat += v;
|
||||||
self.unconfirmedBalanceSat -= v;
|
this.unconfirmedBalanceSat -= v;
|
||||||
self.unconfirmedTxApperances += addSpend;
|
this.unconfirmedTxApperances += addSpend;
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
// spent
|
// spent
|
||||||
self.totalSentSat += v;
|
this.totalSentSat += v;
|
||||||
self.txApperances += addSpend;
|
this.txApperances += addSpend;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
self.unconfirmedBalanceSat += v;
|
this.unconfirmedBalanceSat += v;
|
||||||
self.unconfirmedTxApperances += add;
|
this.unconfirmedTxApperances += add;
|
||||||
}
|
}
|
||||||
});
|
return txs;
|
||||||
return cb();
|
};
|
||||||
});
|
|
||||||
},
|
Address.prototype._setTxs = function(txs) {
|
||||||
], function (err) {
|
|
||||||
|
|
||||||
if (!notxlist) {
|
|
||||||
// sort input and outputs togheter
|
// sort input and outputs togheter
|
||||||
txs.sort(
|
txs.sort(
|
||||||
function compare(a,b) {
|
function compare(a,b) {
|
||||||
|
@ -187,9 +164,33 @@ Address.prototype.update = function(next, notxlist) {
|
||||||
return 0;
|
return 0;
|
||||||
});
|
});
|
||||||
|
|
||||||
self.transactions = txs.map(function(i) { return i.txid; } );
|
this.transactions = txs.map(function(i) { return i.txid; } );
|
||||||
}
|
};
|
||||||
return next(err);
|
|
||||||
|
Address.prototype.update = function(next, notxlist) {
|
||||||
|
var self = this;
|
||||||
|
if (!self.addrStr) return next();
|
||||||
|
|
||||||
|
var txs = [];
|
||||||
|
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){
|
||||||
|
txs=txs.concat(self._addTxItem(txItem, notxlist));
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!notxlist)
|
||||||
|
self._setTxs(txs);
|
||||||
|
return next();
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
@ -91,5 +91,6 @@ module.exports = {
|
||||||
currencyRefresh: 10,
|
currencyRefresh: 10,
|
||||||
keys: {
|
keys: {
|
||||||
segmentio: process.env.INSIGHT_SEGMENTIO_KEY
|
segmentio: process.env.INSIGHT_SEGMENTIO_KEY
|
||||||
}
|
},
|
||||||
|
safeConfirmations: 6, // PLEASE NOTE THAT *FULL RESYNC* IS NEEDED TO CHANGE safeConfirmations
|
||||||
};
|
};
|
||||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -58,3 +58,13 @@ first 10%
|
||||||
Mon Mar 10 11:59:25 ART 2014
|
Mon Mar 10 11:59:25 ART 2014
|
||||||
10% de blk 0 (testnet)
|
10% de blk 0 (testnet)
|
||||||
=> 37s
|
=> 37s
|
||||||
|
|
||||||
|
Thu May 22 13:42:50 ART 2014 (base58check + toString opts + custom getStandardizedObject)
|
||||||
|
10% testnet
|
||||||
|
=> 29s
|
||||||
|
|
||||||
|
|
||||||
|
100% testnet
|
||||||
|
=> 17m6s (user time)
|
||||||
|
|
||||||
|
|
||||||
|
|
269
lib/BlockDb.js
269
lib/BlockDb.js
|
@ -1,16 +1,20 @@
|
||||||
'use strict';
|
'use strict';
|
||||||
var imports = require('soop').imports();
|
var imports = require('soop').imports();
|
||||||
var ThisParent = imports.parent || require('events').EventEmitter;
|
var TIMESTAMP_PREFIX = 'bts-'; // bts-<ts> => <hash>
|
||||||
var TIMESTAMP_PREFIX = 'bts-'; // b-ts-<ts> => <hash>
|
var PREV_PREFIX = 'bpr-'; // bpr-<hash> => <prev_hash>
|
||||||
var PREV_PREFIX = 'bpr-'; // b-prev-<hash> => <prev_hash>
|
var NEXT_PREFIX = 'bne-'; // bne-<hash> => <next_hash>
|
||||||
var NEXT_PREFIX = 'bne-'; // b-next-<hash> => <next_hash>
|
var MAIN_PREFIX = 'bma-'; // bma-<hash> => <height> (0 is unconnected)
|
||||||
var MAIN_PREFIX = 'bma-'; // b-main-<hash> => 1/0
|
var TIP = 'bti-'; // bti = <hash>:<height> last block on the chain
|
||||||
var TIP = 'bti-'; // last block on the chain
|
|
||||||
var LAST_FILE_INDEX = 'file-'; // last processed file index
|
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.
|
* Module dependencies.
|
||||||
*/
|
*/
|
||||||
|
@ -18,15 +22,18 @@ var levelup = require('levelup'),
|
||||||
config = require('../config/config');
|
config = require('../config/config');
|
||||||
var db = imports.db || levelup(config.leveldb + '/blocks',{maxOpenFiles: MAX_OPEN_FILES} );
|
var db = imports.db || levelup(config.leveldb + '/blocks',{maxOpenFiles: MAX_OPEN_FILES} );
|
||||||
var Rpc = imports.rpc || require('./Rpc');
|
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);
|
BlockDb.super(this, arguments);
|
||||||
this.poolMatch = new PoolMatch();
|
|
||||||
};
|
};
|
||||||
BlockDb.parent = ThisParent;
|
|
||||||
|
|
||||||
BlockDb.prototype.close = function(cb) {
|
BlockDb.prototype.close = function(cb) {
|
||||||
db.close(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._addBlockScript = function(b, height) {
|
||||||
//
|
|
||||||
BlockDb.prototype.add = function(b, cb) {
|
|
||||||
var self = this;
|
|
||||||
var time_key = TIMESTAMP_PREFIX +
|
var time_key = TIMESTAMP_PREFIX +
|
||||||
( b.time || Math.round(new Date().getTime() / 1000) );
|
( b.time || Math.round(new Date().getTime() / 1000) );
|
||||||
|
|
||||||
return db.batch()
|
return [
|
||||||
.put(time_key, b.hash)
|
{
|
||||||
.put(MAIN_PREFIX + b.hash, 1)
|
type: 'put',
|
||||||
.put(PREV_PREFIX + b.hash, b.previousblockhash)
|
key: time_key,
|
||||||
.write(function(err){
|
value: b.hash,
|
||||||
if (!err) {
|
},
|
||||||
self.emit('new_block', {blockid: b.hash});
|
{
|
||||||
|
type: 'put',
|
||||||
|
key: MAIN_PREFIX + b.hash,
|
||||||
|
value: height,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'put',
|
||||||
|
key:PREV_PREFIX + b.hash,
|
||||||
|
value: b.previousblockhash,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
};
|
||||||
|
|
||||||
|
BlockDb.prototype._delTxsScript = function(txs) {
|
||||||
|
var dbScript =[];
|
||||||
|
|
||||||
|
for(var ii in txs){
|
||||||
|
dbScript.push({
|
||||||
|
type: 'del',
|
||||||
|
key: IN_BLK_PREFIX + txs[ii],
|
||||||
|
});
|
||||||
}
|
}
|
||||||
cb(err);
|
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._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) {
|
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) {
|
db.get(TIP, function(err, val) {
|
||||||
return cb(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, cb) {
|
BlockDb.prototype.setTip = function(hash, height, cb) {
|
||||||
db.put(TIP, hash, function(err) {
|
this.cachedTip = hash + ':' + height;
|
||||||
|
db.put(TIP, this.cachedTip, function(err) {
|
||||||
return cb(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
|
//mainly for testing
|
||||||
BlockDb.prototype.setPrev = function(hash, prevHash, cb) {
|
BlockDb.prototype.setPrev = function(hash, prevHash, cb) {
|
||||||
db.put(PREV_PREFIX + hash, prevHash, function(err) {
|
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) {
|
db.get(MAIN_PREFIX + hash, function(err, val) {
|
||||||
if (err && err.notFound) { err = null; val = 0;}
|
if (err && err.notFound) { err = null; val = 0;}
|
||||||
return cb(err,parseInt(val));
|
return cb(err,parseInt(val));
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
BlockDb.prototype.setMain = function(hash, isMain, cb) {
|
BlockDb.prototype._setHeightScript = function(hash, height) {
|
||||||
if (!isMain) console.log('\tNew orphan: %s',hash);
|
d('setHeight: %s #%d', hash,height);
|
||||||
db.put(MAIN_PREFIX + hash, isMain?1:0, function(err) {
|
return ([{
|
||||||
return cb(err);
|
type: 'put',
|
||||||
});
|
key: MAIN_PREFIX + hash,
|
||||||
|
value: height,
|
||||||
|
}]);
|
||||||
};
|
};
|
||||||
|
|
||||||
BlockDb.prototype.setNext = function(hash, nextHash, cb) {
|
BlockDb.prototype.setNext = function(hash, nextHash, cb) {
|
||||||
db.put(NEXT_PREFIX + hash, nextHash, function(err) {
|
db.put(NEXT_PREFIX + hash, nextHash, function(err) {
|
||||||
return cb(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) {
|
BlockDb.prototype.fromHashWithInfo = function(hash, cb) {
|
||||||
var self = this;
|
var self = this;
|
||||||
|
|
||||||
Rpc.getBlock(hash, function(err, info) {
|
Rpc.getBlock(hash, function(err, info) {
|
||||||
if (err || !info) return cb(err);
|
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);
|
if (err) return cb(err);
|
||||||
|
|
||||||
info.isMainChain = val ? true : false;
|
info.isMainChain = height ? true : false;
|
||||||
|
|
||||||
return cb(null, {
|
return cb(null, {
|
||||||
hash: hash,
|
hash: hash,
|
||||||
|
@ -223,4 +324,64 @@ BlockDb.prototype.blockIndex = function(height, cb) {
|
||||||
return Rpc.blockIndex(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);
|
module.exports = require('soop')(BlockDb);
|
||||||
|
|
|
@ -2,24 +2,21 @@
|
||||||
|
|
||||||
var imports = require('soop').imports();
|
var imports = require('soop').imports();
|
||||||
var util = require('util');
|
var util = require('util');
|
||||||
var assert = require('assert');
|
|
||||||
var async = require('async');
|
var async = require('async');
|
||||||
|
|
||||||
var bitcore = require('bitcore');
|
var bitcore = require('bitcore');
|
||||||
var RpcClient = bitcore.RpcClient;
|
|
||||||
var Script = bitcore.Script;
|
|
||||||
var networks = bitcore.networks;
|
var networks = bitcore.networks;
|
||||||
var config = imports.config || require('../config/config');
|
var config = imports.config || require('../config/config');
|
||||||
var Sync = require('./Sync');
|
var Sync = require('./Sync');
|
||||||
var sockets = require('../app/controllers/socket.js');
|
var sockets = require('../app/controllers/socket.js');
|
||||||
var BlockExtractor = require('./BlockExtractor.js');
|
var BlockExtractor = require('./BlockExtractor.js');
|
||||||
var buffertools = require('buffertools');
|
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 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 = '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:';
|
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);
|
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() {
|
HistoricSync.prototype.showProgress = function() {
|
||||||
var self = this;
|
var self = this;
|
||||||
|
|
||||||
if ( self.status ==='syncing' &&
|
if ( self.status ==='syncing' &&
|
||||||
( self.syncedBlocks ) % self.step !== 1) return;
|
( self.syncedBlocks ) % self.step !== 1) return;
|
||||||
|
|
||||||
if (self.error) {
|
if (self.error)
|
||||||
p('ERROR: ' + self.error);
|
error(self.error);
|
||||||
}
|
|
||||||
else {
|
else {
|
||||||
self.updatePercentage();
|
self.updatePercentage();
|
||||||
p(util.format('status: [%d%%]', self.syncPercentage));
|
info(util.format('status: [%d%%]', self.syncPercentage));
|
||||||
}
|
}
|
||||||
if (self.shouldBroadcast) {
|
if (self.shouldBroadcast) {
|
||||||
sockets.broadcastSyncInfo(self.info());
|
sockets.broadcastSyncInfo(self.info());
|
||||||
}
|
}
|
||||||
|
//
|
||||||
// if (self.syncPercentage > 10) {
|
// if (self.syncPercentage > 10) {
|
||||||
// process.exit(-1);
|
// 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) {
|
HistoricSync.prototype.getBlockFromFile = function(cb) {
|
||||||
var self = this;
|
var self = this;
|
||||||
|
|
||||||
|
@ -141,36 +146,7 @@ HistoricSync.prototype.getBlockFromFile = function(cb) {
|
||||||
//get Info
|
//get Info
|
||||||
self.blockExtractor.getNextBlock(function(err, b) {
|
self.blockExtractor.getNextBlock(function(err, b) {
|
||||||
if (err || ! b) return cb(err);
|
if (err || ! b) return cb(err);
|
||||||
blockInfo = b.getStandardizedObject(b.txs, self.network);
|
blockInfo = self.getStandardizedBlock(b);
|
||||||
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++;
|
|
||||||
});
|
|
||||||
});
|
|
||||||
self.sync.bDb.setLastFileIndex(self.blockExtractor.currentFileIndex, function(err) {
|
self.sync.bDb.setLastFileIndex(self.blockExtractor.currentFileIndex, function(err) {
|
||||||
return cb(err,blockInfo);
|
return cb(err,blockInfo);
|
||||||
});
|
});
|
||||||
|
@ -235,7 +211,7 @@ HistoricSync.prototype.updateStartBlock = function(next) {
|
||||||
self.sync.bDb.fromHashWithInfo(tip, function(err, bi) {
|
self.sync.bDb.fromHashWithInfo(tip, function(err, bi) {
|
||||||
blockInfo = bi ? bi.info : {};
|
blockInfo = bi ? bi.info : {};
|
||||||
if (oldtip)
|
if (oldtip)
|
||||||
self.sync.setBlockMain(oldtip, false, cb);
|
self.sync.setBlockHeight(oldtip, -1, cb);
|
||||||
else
|
else
|
||||||
return cb();
|
return cb();
|
||||||
});
|
});
|
||||||
|
@ -249,16 +225,18 @@ HistoricSync.prototype.updateStartBlock = function(next) {
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
oldtip = tip;
|
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;
|
tip = blockInfo.previousblockhash;
|
||||||
assert(tip);
|
info('Previous TIP is now orphan. Back to:' + tip);
|
||||||
p('Previous TIP is now orphan. Back to:' + tip);
|
|
||||||
ret = true;
|
ret = true;
|
||||||
}
|
}
|
||||||
return ret;
|
return ret;
|
||||||
},
|
},
|
||||||
function(err) {
|
function(err) {
|
||||||
self.startBlock = tip;
|
self.startBlock = tip;
|
||||||
p('Resuming sync from block:'+tip);
|
info('Resuming sync from block:'+tip);
|
||||||
return next(err);
|
return next(err);
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
@ -275,7 +253,7 @@ HistoricSync.prototype.prepareFileSync = function(opts, next) {
|
||||||
try {
|
try {
|
||||||
self.blockExtractor = new BlockExtractor(config.bitcoind.dataDir, config.network);
|
self.blockExtractor = new BlockExtractor(config.bitcoind.dataDir, config.network);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
p(e.message + '. Disabling file sync.');
|
info(e.message + '. Disabling file sync.');
|
||||||
return next();
|
return next();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -288,7 +266,7 @@ HistoricSync.prototype.prepareFileSync = function(opts, next) {
|
||||||
|
|
||||||
var h = self.genesis;
|
var h = self.genesis;
|
||||||
|
|
||||||
p('Seeking file to:' + self.startBlock);
|
info('Seeking file to:' + self.startBlock);
|
||||||
//forward till startBlock
|
//forward till startBlock
|
||||||
async.whilst(
|
async.whilst(
|
||||||
function() {
|
function() {
|
||||||
|
@ -312,26 +290,26 @@ HistoricSync.prototype.prepareRpcSync = function(opts, next) {
|
||||||
|
|
||||||
if (self.blockExtractor) return next();
|
if (self.blockExtractor) return next();
|
||||||
self.getFn = self.getBlockFromRPC;
|
self.getFn = self.getBlockFromRPC;
|
||||||
|
self.allowReorgs = true;
|
||||||
self.currentRpcHash = self.startBlock;
|
self.currentRpcHash = self.startBlock;
|
||||||
self.allowReorgs = false;
|
|
||||||
return next();
|
return next();
|
||||||
};
|
};
|
||||||
|
|
||||||
HistoricSync.prototype.showSyncStartMessage = function() {
|
HistoricSync.prototype.showSyncStartMessage = function() {
|
||||||
var self = this;
|
var self = this;
|
||||||
|
|
||||||
p('Got ' + self.connectedCountDB +
|
info('Got ' + self.connectedCountDB +
|
||||||
' blocks in current DB, out of ' + self.blockChainHeight + ' block at bitcoind');
|
' blocks in current DB, out of ' + self.blockChainHeight + ' block at bitcoind');
|
||||||
|
|
||||||
if (self.blockExtractor) {
|
if (self.blockExtractor) {
|
||||||
p('bitcoind dataDir configured...importing blocks from .dat files');
|
info('bitcoind dataDir configured...importing blocks from .dat files');
|
||||||
p('First file index: ' + self.blockExtractor.currentFileIndex);
|
info('First file index: ' + self.blockExtractor.currentFileIndex);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
p('syncing from RPC (slow)');
|
info('syncing from RPC (slow)');
|
||||||
}
|
}
|
||||||
|
|
||||||
p('Starting from: ', self.startBlock);
|
info('Starting from: ', self.startBlock);
|
||||||
self.showProgress();
|
self.showProgress();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -389,7 +367,7 @@ HistoricSync.prototype.start = function(opts, next) {
|
||||||
var self = this;
|
var self = this;
|
||||||
|
|
||||||
if (self.status==='starting' || self.status==='syncing') {
|
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();
|
return next();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -404,19 +382,16 @@ HistoricSync.prototype.start = function(opts, next) {
|
||||||
function (w_cb) {
|
function (w_cb) {
|
||||||
self.getFn(function(err,blockInfo) {
|
self.getFn(function(err,blockInfo) {
|
||||||
if (err) return w_cb(self.setError(err));
|
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.syncedBlocks++;
|
||||||
self.sync.storeTipBlock(blockInfo, self.allowReorgs, function(err) {
|
self.sync.storeTipBlock(blockInfo, self.allowReorgs, function(err) {
|
||||||
if (err) return w_cb(self.setError(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(){
|
setImmediate(function(){
|
||||||
return w_cb(err);
|
return w_cb(err);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
self.endTs = Date.now();
|
self.endTs = Date.now();
|
||||||
|
|
|
@ -49,10 +49,8 @@ PeerSync.prototype.handleInv = function(info) {
|
||||||
|
|
||||||
PeerSync.prototype.handleTx = function(info) {
|
PeerSync.prototype.handleTx = function(info) {
|
||||||
var self =this;
|
var self =this;
|
||||||
var tx = info.message.tx.getStandardizedObject();
|
var tx = this.sync.txDb.getStandardizedTx(info.message.tx);
|
||||||
tx.outs = info.message.tx.outs;
|
console.log('[p2p_sync] Handle tx: ' + tx.txid);
|
||||||
tx.ins = info.message.tx.ins;
|
|
||||||
console.log('[p2p_sync] Handle tx: ' + tx.hash);
|
|
||||||
tx.time = tx.time || Math.round(new Date().getTime() / 1000);
|
tx.time = tx.time || Math.round(new Date().getTime() / 1000);
|
||||||
|
|
||||||
this.sync.storeTxs([tx], function(err) {
|
this.sync.storeTxs([tx], function(err) {
|
||||||
|
@ -62,10 +60,10 @@ PeerSync.prototype.handleTx = function(info) {
|
||||||
else {
|
else {
|
||||||
if (self.shouldBroadcast) {
|
if (self.shouldBroadcast) {
|
||||||
sockets.broadcastTx(tx);
|
sockets.broadcastTx(tx);
|
||||||
if (tx.addrsToEmit) {
|
if (tx.relatedAddrs) {
|
||||||
tx.addrsToEmit.forEach(function(a) {
|
for(var ii in tx.relatedAddrs){
|
||||||
sockets.broadcastAddressTx(a, tx.txid);
|
sockets.broadcastAddressTx(tx.relatedAddrs[ii], tx.txid);
|
||||||
});
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -77,7 +75,6 @@ PeerSync.prototype.handleBlock = function(info) {
|
||||||
var self = this;
|
var self = this;
|
||||||
var block = info.message.block;
|
var block = info.message.block;
|
||||||
var blockHash = bitcoreUtil.formatHashFull(block.calcHash());
|
var blockHash = bitcoreUtil.formatHashFull(block.calcHash());
|
||||||
|
|
||||||
console.log('[p2p_sync] Handle block: %s (allowReorgs: %s)', blockHash, self.allowReorgs);
|
console.log('[p2p_sync] Handle block: %s (allowReorgs: %s)', blockHash, self.allowReorgs);
|
||||||
|
|
||||||
var tx_hashes = block.txs.map(function(tx) {
|
var tx_hashes = block.txs.map(function(tx) {
|
||||||
|
|
141
lib/Sync.js
141
lib/Sync.js
|
@ -7,6 +7,12 @@ var bitcore = require('bitcore');
|
||||||
var networks = bitcore.networks;
|
var networks = bitcore.networks;
|
||||||
var async = require('async');
|
var async = require('async');
|
||||||
|
|
||||||
|
var logger = require('./logger').logger;
|
||||||
|
var d = logger.log;
|
||||||
|
var info = logger.info;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
var syncId = 0;
|
var syncId = 0;
|
||||||
|
|
||||||
function Sync(opts) {
|
function Sync(opts) {
|
||||||
|
@ -15,6 +21,7 @@ function Sync(opts) {
|
||||||
this.bDb = require('./BlockDb').default();
|
this.bDb = require('./BlockDb').default();
|
||||||
this.txDb = require('./TransactionDb').default();
|
this.txDb = require('./TransactionDb').default();
|
||||||
this.network = config.network === 'testnet' ? networks.testnet : networks.livenet;
|
this.network = config.network === 'testnet' ? networks.testnet : networks.livenet;
|
||||||
|
this.cachedLastHash = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
Sync.prototype.close = function(cb) {
|
Sync.prototype.close = function(cb) {
|
||||||
|
@ -56,7 +63,8 @@ Sync.prototype.destroy = function(next) {
|
||||||
* \
|
* \
|
||||||
* F-G-NEW
|
* F-G-NEW
|
||||||
* 1) Set F-G as connected (mark TXs as valid)
|
* 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)
|
* Case 3)
|
||||||
|
@ -77,39 +85,40 @@ Sync.prototype.storeTipBlock = function(b, allowReorgs, cb) {
|
||||||
if (!b) return cb();
|
if (!b) return cb();
|
||||||
|
|
||||||
var self = this;
|
var self = this;
|
||||||
var oldTip, oldNext, needReorg = false;
|
var oldTip, oldNext, oldHeight, needReorg = false, height = -1;
|
||||||
var newPrev = b.previousblockhash;
|
var newPrev = b.previousblockhash;
|
||||||
|
|
||||||
async.series([
|
async.series([
|
||||||
|
|
||||||
function(c) {
|
function(c) {
|
||||||
|
// TODO? remove this check?
|
||||||
self.bDb.has(b.hash, function(err, val) {
|
self.bDb.has(b.hash, function(err, val) {
|
||||||
return c(err ||
|
return c(err ||
|
||||||
(val ? new Error('WARN: Ignoring already existing block:' + b.hash) : null));
|
(val ? new Error('WARN: Ignoring already existing block:' + b.hash) : null));
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
function(c) {
|
function(c) {
|
||||||
if (!allowReorgs) return c();
|
if (!allowReorgs || newPrev === self.cachedLastHash) return c();
|
||||||
self.bDb.has(newPrev, function(err, val) {
|
self.bDb.has(newPrev, function(err, val) {
|
||||||
|
// Genesis? no problem
|
||||||
if (!val && newPrev.match(/^0+$/)) return c();
|
if (!val && newPrev.match(/^0+$/)) return c();
|
||||||
|
|
||||||
return c(err ||
|
return c(err ||
|
||||||
(!val ? new Error('NEED_SYNC Ignoring block with non existing prev:' + b.hash) : null));
|
(!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) {
|
function(c) {
|
||||||
if (!allowReorgs) return c();
|
if (!allowReorgs) return c();
|
||||||
self.bDb.getTip(function(err, val) {
|
self.bDb.getTip(function(err, hash, h) {
|
||||||
oldTip = val;
|
oldTip = hash;
|
||||||
if (oldTip && newPrev !== oldTip) needReorg = true;
|
oldHeight = hash ? (h || 0) : -1
|
||||||
|
|
||||||
|
if (oldTip && newPrev !== oldTip) {
|
||||||
|
needReorg = true;
|
||||||
|
console.log('## REORG Triggered, tip mismatch');
|
||||||
|
}
|
||||||
return c();
|
return c();
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
function(c) {
|
function(c) {
|
||||||
if (!needReorg) return c();
|
if (!needReorg) return c();
|
||||||
self.bDb.getNext(newPrev, function(err, val) {
|
self.bDb.getNext(newPrev, function(err, val) {
|
||||||
|
@ -119,16 +128,28 @@ Sync.prototype.storeTipBlock = function(b, allowReorgs, cb) {
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
function(c) {
|
function(c) {
|
||||||
self.bDb.add(b, 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) {
|
function(c) {
|
||||||
if (!needReorg) return c();
|
self.cachedLastHash = b.hash; // just for speed up.
|
||||||
console.log('NEW TIP: %s NEED REORG (old tip: %s)', b.hash, oldTip);
|
self.bDb.add(b, height, c);
|
||||||
self.processReorg(oldTip, oldNext, newPrev, c);
|
|
||||||
},
|
},
|
||||||
function(c) {
|
function(c) {
|
||||||
if (!allowReorgs) return c();
|
if (!allowReorgs) return c();
|
||||||
self.bDb.setTip(b.hash, function(err) {
|
self.bDb.setTip(b.hash, height, function(err) {
|
||||||
return c(err);
|
return c(err);
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
@ -147,21 +168,20 @@ Sync.prototype.storeTipBlock = function(b, allowReorgs, cb) {
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
Sync.prototype.processReorg = function(oldTip, oldNext, newPrev, oldHeight, cb) {
|
||||||
|
|
||||||
Sync.prototype.processReorg = function(oldTip, oldNext, newPrev, cb) {
|
|
||||||
var self = this;
|
var self = this;
|
||||||
|
|
||||||
var orphanizeFrom;
|
var orphanizeFrom, newHeight;
|
||||||
|
|
||||||
async.series([
|
async.series([
|
||||||
|
|
||||||
function(c) {
|
function(c) {
|
||||||
self.bDb.isMain(newPrev, function(err, val) {
|
self.bDb.getHeight(newPrev, function(err, height) {
|
||||||
if (!val) return c();
|
if (!height) return c(new Error('Could not found block:' + newPrev));
|
||||||
|
if (height<0) return c();
|
||||||
|
|
||||||
console.log('# Reorg Case 1)');
|
newHeight = height + 1;
|
||||||
// case 1
|
info('# Reorg Case 1) OldNext: %s NewHeight: %d', oldNext, newHeight);
|
||||||
orphanizeFrom = oldNext;
|
orphanizeFrom = oldNext;
|
||||||
return c(err);
|
return c(err);
|
||||||
});
|
});
|
||||||
|
@ -169,10 +189,12 @@ Sync.prototype.processReorg = function(oldTip, oldNext, newPrev, cb) {
|
||||||
function(c) {
|
function(c) {
|
||||||
if (orphanizeFrom) return c();
|
if (orphanizeFrom) return c();
|
||||||
|
|
||||||
console.log('# Reorg Case 2)');
|
info('# Reorg Case 2)');
|
||||||
self.setBranchConnectedBackwards(newPrev, function(err, yHash, newYHashNext) {
|
self.setBranchConnectedBackwards(newPrev, function(err, yHash, newYHashNext, height) {
|
||||||
if (err) return c(err);
|
if (err) return c(err);
|
||||||
|
newHeight = height;
|
||||||
self.bDb.getNext(yHash, function(err, yHashNext) {
|
self.bDb.getNext(yHash, function(err, yHashNext) {
|
||||||
|
// Connect the new branch, and orphanize the old one.
|
||||||
orphanizeFrom = yHashNext;
|
orphanizeFrom = yHashNext;
|
||||||
self.bDb.setNext(yHash, newYHashNext, function(err) {
|
self.bDb.setNext(yHash, newYHashNext, function(err) {
|
||||||
return c(err);
|
return c(err);
|
||||||
|
@ -182,25 +204,17 @@ Sync.prototype.processReorg = function(oldTip, oldNext, newPrev, cb) {
|
||||||
},
|
},
|
||||||
function(c) {
|
function(c) {
|
||||||
if (!orphanizeFrom) return c();
|
if (!orphanizeFrom) return c();
|
||||||
self.setBranchOrphan(orphanizeFrom, function(err) {
|
self._setBranchOrphan(orphanizeFrom, function(err) {
|
||||||
return c(err);
|
return c(err);
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
function(err) {
|
function(err) {
|
||||||
return cb(err);
|
return cb(err, newHeight);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
Sync.prototype.setBlockMain = function(hash, isMain, cb) {
|
Sync.prototype._setBranchOrphan = function(fromHash, 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) {
|
|
||||||
var self = this,
|
var self = this,
|
||||||
hashInterator = fromHash;
|
hashInterator = fromHash;
|
||||||
|
|
||||||
|
@ -209,7 +223,7 @@ Sync.prototype.setBranchOrphan = function(fromHash, cb) {
|
||||||
return hashInterator;
|
return hashInterator;
|
||||||
},
|
},
|
||||||
function(c) {
|
function(c) {
|
||||||
self.setBlockMain(hashInterator, false, function(err) {
|
self.bDb.setBlockNotMain(hashInterator, function(err) {
|
||||||
if (err) return cb(err);
|
if (err) return cb(err);
|
||||||
self.bDb.getNext(hashInterator, function(err, val) {
|
self.bDb.getNext(hashInterator, function(err, val) {
|
||||||
hashInterator = val;
|
hashInterator = val;
|
||||||
|
@ -220,44 +234,53 @@ Sync.prototype.setBranchOrphan = function(fromHash, cb) {
|
||||||
};
|
};
|
||||||
|
|
||||||
Sync.prototype.setBranchConnectedBackwards = function(fromHash, cb) {
|
Sync.prototype.setBranchConnectedBackwards = function(fromHash, cb) {
|
||||||
|
//console.log('[Sync.js.219:setBranchConnectedBackwards:]',fromHash); //TODO
|
||||||
var self = this,
|
var self = this,
|
||||||
hashInterator = fromHash,
|
hashInterator = fromHash,
|
||||||
lastHash = fromHash,
|
lastHash = fromHash,
|
||||||
isMain;
|
yHeight,
|
||||||
|
branch = [];
|
||||||
|
|
||||||
async.doWhilst(
|
async.doWhilst(
|
||||||
function(c) {
|
function(c) {
|
||||||
self.setBlockMain(hashInterator, true, function(err) {
|
branch.unshift(hashInterator);
|
||||||
if (err) return c(err);
|
|
||||||
self.bDb.getPrev(hashInterator, function(err, val) {
|
self.bDb.getPrev(hashInterator, function(err, val) {
|
||||||
if (err) return c(err);
|
if (err) return c(err);
|
||||||
lastHash = hashInterator;
|
lastHash = hashInterator;
|
||||||
hashInterator = val;
|
hashInterator = val;
|
||||||
self.bDb.isMain(hashInterator, function(err, val) {
|
self.bDb.getHeight(hashInterator, function(err, height) {
|
||||||
isMain = val;
|
yHeight = height;
|
||||||
return c();
|
return c();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
|
||||||
},
|
},
|
||||||
function() {
|
function() {
|
||||||
return hashInterator && !isMain;
|
return hashInterator && yHeight<=0;
|
||||||
|
},
|
||||||
|
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) {
|
function(err) {
|
||||||
console.log('\tFound yBlock:', hashInterator);
|
return cb(err, hashInterator, lastHash, heightIter);
|
||||||
return cb(err, hashInterator, lastHash);
|
});
|
||||||
}
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
Sync.prototype.storeTxs = function(txs, cb) {
|
|
||||||
var self = this;
|
|
||||||
self.txDb.createFromArray(txs, null, function(err) {
|
|
||||||
if (err) return cb(err);
|
|
||||||
return cb(err);
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
//Store unconfirmed TXs
|
||||||
|
Sync.prototype.storeTxs = function(txs, cb) {
|
||||||
|
this.txDb.addMany(txs, cb);
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
module.exports = require('soop')(Sync);
|
module.exports = require('soop')(Sync);
|
||||||
|
|
|
@ -2,11 +2,6 @@
|
||||||
|
|
||||||
var imports = require('soop').imports();
|
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
|
// to show tx outs
|
||||||
var OUTS_PREFIX = 'txo-'; //txo-<txid>-<n> => [addr, btc_sat]
|
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
|
// TODO: use bitcore networks module
|
||||||
var genesisTXID = '4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b';
|
var genesisTXID = '4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b';
|
||||||
var CONCURRENCY = 10;
|
var CONCURRENCY = 10;
|
||||||
|
var DEFAULT_SAFE_CONFIRMATIONS = 6;
|
||||||
|
|
||||||
var MAX_OPEN_FILES = 500;
|
var MAX_OPEN_FILES = 500;
|
||||||
// var CONFIRMATION_NR_TO_NOT_CHECK = 10; //Spend
|
// var CONFIRMATION_NR_TO_NOT_CHECK = 10; //Spend
|
||||||
|
@ -32,25 +28,36 @@ var bitcore = require('bitcore'),
|
||||||
levelup = require('levelup'),
|
levelup = require('levelup'),
|
||||||
async = require('async'),
|
async = require('async'),
|
||||||
config = require('../config/config'),
|
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 db = imports.db || levelup(config.leveldb + '/txs',{maxOpenFiles: MAX_OPEN_FILES} );
|
||||||
var Script = bitcore.Script;
|
var PoolMatch = imports.poolMatch || require('soop').load('./PoolMatch',config);
|
||||||
// This is 0.1.2 = > c++ version of base57-native
|
// This is 0.1.2 = > c++ version of base58-native
|
||||||
var base58 = require('base58-native').base58Check;
|
var base58 = require('base58-native').base58Check;
|
||||||
var encodedData = require('soop').load('bitcore/util/EncodedData',{
|
var encodedData = require('soop').load('bitcore/util/EncodedData',{
|
||||||
base58: base58
|
base58: base58
|
||||||
});
|
});
|
||||||
var versionedData= require('soop').load('bitcore/util/VersionedData',{
|
var versionedData= require('soop').load('bitcore/util/VersionedData',{
|
||||||
parent: encodedData
|
parent: encodedData
|
||||||
});
|
});
|
||||||
|
|
||||||
var Address = require('soop').load('bitcore/lib/Address',{
|
var Address = require('soop').load('bitcore/lib/Address',{
|
||||||
parent: versionedData
|
parent: versionedData
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
var TransactionDb = function() {
|
var TransactionDb = function() {
|
||||||
TransactionDb.super(this, arguments);
|
TransactionDb.super(this, arguments);
|
||||||
this.network = config.network === 'testnet' ? networks.testnet : networks.livenet;
|
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) {
|
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) {
|
TransactionDb.prototype._addSpentInfo = function(r, txid, index, ts) {
|
||||||
if (r.spentTxId) {
|
if (r.spentTxId) {
|
||||||
if (!r.multipleSpentAttempts) {
|
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;
|
var self = this;
|
||||||
|
|
||||||
if (!info || info.isCoinBase) return cb();
|
if (!txInfo || txInfo.isCoinBase) return cb();
|
||||||
|
|
||||||
var valueIn = 0;
|
var valueIn = 0;
|
||||||
var incompleteInputs = 0;
|
var incompleteInputs = 0;
|
||||||
|
|
||||||
async.eachLimit(info.vin, CONCURRENCY, function(i, c_in) {
|
async.eachLimit(txInfo.vin, CONCURRENCY, function(i, c_in) {
|
||||||
self.fromTxIdN(i.txid, i.vout, info.confirmations, function(err, ret) {
|
self.fromTxIdN(i.txid, i.vout, txInfo.confirmations, function(err, ret) {
|
||||||
//console.log('[TransactionDb.js.154:ret:]',ret); //TODO
|
|
||||||
if (!ret || !ret.addr || !ret.valueSat) {
|
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;
|
if (ret) i.unconfirmedInput = ret.unconfirmedInput;
|
||||||
incompleteInputs = 1;
|
incompleteInputs = 1;
|
||||||
return c_in(); // error not scalated
|
return c_in(); // error not scalated
|
||||||
}
|
}
|
||||||
|
|
||||||
info.firstSeenTs = ret.spentTs;
|
txInfo.firstSeenTs = ret.spentTs;
|
||||||
i.unconfirmedInput = i.unconfirmedInput;
|
i.unconfirmedInput = i.unconfirmedInput;
|
||||||
i.addr = ret.addr;
|
i.addr = ret.addr;
|
||||||
i.valueSat = ret.valueSat;
|
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
|
* If confirmed by bitcoind, we could not check for double spents
|
||||||
* but we prefer to keep the flag of double spent attempt
|
* but we prefer to keep the flag of double spent attempt
|
||||||
*
|
*
|
||||||
if (info.confirmations
|
if (txInfo.confirmations
|
||||||
&& info.confirmations >= CONFIRMATION_NR_TO_NOT_CHECK)
|
&& txInfo.confirmations >= CONFIRMATION_NR_TO_NOT_CHECK)
|
||||||
return c_in();
|
return c_in();
|
||||||
isspent
|
isspent
|
||||||
*/
|
*/
|
||||||
// Double spent?
|
// Double spent?
|
||||||
if (ret.multipleSpentAttempt || !ret.spentTxId ||
|
if (ret.multipleSpentAttempt || !ret.spentTxId ||
|
||||||
(ret.spentTxId && ret.spentTxId !== info.txid)
|
(ret.spentTxId && ret.spentTxId !== txInfo.txid)
|
||||||
) {
|
) {
|
||||||
if (ret.multipleSpentAttempts) {
|
if (ret.multipleSpentAttempts) {
|
||||||
ret.multipleSpentAttempts.forEach(function(mul) {
|
ret.multipleSpentAttempts.forEach(function(mul) {
|
||||||
if (mul.spentTxId !== info.txid) {
|
if (mul.spentTxId !== txInfo.txid) {
|
||||||
i.doubleSpentTxID = ret.spentTxId;
|
i.doubleSpentTxID = ret.spentTxId;
|
||||||
i.doubleSpentIndex = ret.spentIndex;
|
i.doubleSpentIndex = ret.spentIndex;
|
||||||
}
|
}
|
||||||
|
@ -240,10 +227,10 @@ isspent
|
||||||
},
|
},
|
||||||
function() {
|
function() {
|
||||||
if (!incompleteInputs) {
|
if (!incompleteInputs) {
|
||||||
info.valueIn = valueIn / util.COIN;
|
txInfo.valueIn = valueIn / util.COIN;
|
||||||
info.fees = (valueIn - (info.valueOut * util.COIN)).toFixed(0) / util.COIN;
|
txInfo.fees = (valueIn - (txInfo.valueOut * util.COIN)).toFixed(0) / util.COIN;
|
||||||
} else {
|
} else {
|
||||||
info.incompleteInputs = 1;
|
txInfo.incompleteInputs = 1;
|
||||||
}
|
}
|
||||||
return cb();
|
return cb();
|
||||||
});
|
});
|
||||||
|
@ -252,12 +239,11 @@ isspent
|
||||||
TransactionDb.prototype._getInfo = function(txid, next) {
|
TransactionDb.prototype._getInfo = function(txid, next) {
|
||||||
var self = this;
|
var self = this;
|
||||||
|
|
||||||
Rpc.getTxInfo(txid, function(err, info) {
|
Rpc.getTxInfo(txid, function(err, txInfo) {
|
||||||
if (err) return next(err);
|
if (err) return next(err);
|
||||||
|
self._fillOutpoints(txInfo, function() {
|
||||||
self._fillOutpoints(info, function() {
|
self._fillSpent(txInfo, function() {
|
||||||
self._fillSpent(info, function() {
|
return next(null, txInfo);
|
||||||
return next(null, info);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -306,7 +292,7 @@ TransactionDb.prototype.fromTxIdN = function(txid, n, confirmations, cb) {
|
||||||
/*
|
/*
|
||||||
* If this TxID comes from an RPC request
|
* If this TxID comes from an RPC request
|
||||||
* the .confirmations value from bitcoind is available
|
* 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%
|
* 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;
|
var self = this;
|
||||||
|
|
||||||
self.isConfirmed(o.txid, function(err, is) {
|
var dbScript=[];
|
||||||
if (err) return cb(err);
|
for(var ii in txouts){
|
||||||
|
var txout=txouts[ii];
|
||||||
|
|
||||||
o.isConfirmed = is;
|
//everything already cached?
|
||||||
if (!o.spentTxId) return cb();
|
if (txout.spentIsConfirmedCached) {
|
||||||
|
continue;
|
||||||
if (o.multipleSpentAttempts) {
|
|
||||||
|
|
||||||
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();
|
|
||||||
});
|
var infoToCache = [];
|
||||||
}, cb);
|
if (txout.confirmations > self.safeConfirmations) {
|
||||||
} else {
|
if (!txout.isConfirmedCached) infoToCache.push(1);
|
||||||
self.isConfirmed(o.spentTxId, function(err, is) {
|
|
||||||
if (err) return cb(err);
|
if (txout.spentConfirmations > self.safeConfirmations) {
|
||||||
o.spentIsConfirmed = is;
|
// console.log('[TransactionDb.js.309]',txout); //TODO
|
||||||
return cb();
|
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) {
|
TransactionDb.prototype.fromAddr = function(addr, cb) {
|
||||||
var self = this;
|
var self = this;
|
||||||
|
|
||||||
var k = ADDR_PREFIX + addr + '-';
|
var k = ADDR_PREFIX + addr + '-';
|
||||||
var ret = [];
|
var ret = [];
|
||||||
|
|
||||||
|
@ -378,21 +455,11 @@ TransactionDb.prototype.fromAddr = function(addr, cb) {
|
||||||
end: k + '~'
|
end: k + '~'
|
||||||
})
|
})
|
||||||
.on('data', function(data) {
|
.on('data', function(data) {
|
||||||
var k = data.key.split('-');
|
ret.push(self._parseAddrData(data));
|
||||||
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);
|
|
||||||
})
|
})
|
||||||
|
.on('error', cb)
|
||||||
.on('end', function() {
|
.on('end', function() {
|
||||||
|
async.eachLimit(ret.filter(function(x){return !x.spentIsConfirmed;}), CONCURRENCY, function(o, e_c) {
|
||||||
async.eachLimit(ret, CONCURRENCY, function(o, e_c) {
|
|
||||||
var k = SPENT_PREFIX + o.txid + '-' + o.index + '-';
|
var k = SPENT_PREFIX + o.txid + '-' + o.index + '-';
|
||||||
db.createReadStream({
|
db.createReadStream({
|
||||||
start: k,
|
start: k,
|
||||||
|
@ -402,28 +469,75 @@ TransactionDb.prototype.fromAddr = function(addr, cb) {
|
||||||
var k = data.key.split('-');
|
var k = data.key.split('-');
|
||||||
self._addSpentInfo(o, k[3], k[4], data.value);
|
self._addSpentInfo(o, k[3], k[4], data.value);
|
||||||
})
|
})
|
||||||
.on('error', function(err) {
|
.on('error', e_c)
|
||||||
return e_c(err);
|
.on('end', e_c);
|
||||||
})
|
|
||||||
.on('end', function(err) {
|
|
||||||
return e_c(err);
|
|
||||||
});
|
|
||||||
},
|
},
|
||||||
function() {
|
function(err) {
|
||||||
async.eachLimit(ret, CONCURRENCY, function(o, e_c) {
|
|
||||||
self.fillConfirmations(o, e_c);
|
|
||||||
}, function(err) {
|
|
||||||
return cb(err, ret);
|
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) {
|
TransactionDb.prototype.removeFromTxId = function(txid, cb) {
|
||||||
|
|
||||||
async.series([
|
async.series([
|
||||||
|
|
||||||
function(c) {
|
function(c) {
|
||||||
db.createReadStream({
|
db.createReadStream({
|
||||||
start: OUTS_PREFIX + txid + '-',
|
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;
|
|
||||||
|
|
||||||
|
TransactionDb.prototype._addScript = function(tx) {
|
||||||
var to = 0;
|
var relatedAddrs = [];
|
||||||
var tx = txInfo;
|
var dbScript = [];
|
||||||
if (tx.outs) {
|
var ts = tx.time;
|
||||||
tx.outs.forEach(function(o) {
|
var txid = tx.txid || tx.hash;
|
||||||
var s = new Script(o.s);
|
// var u=require('util');
|
||||||
var addrs = new Address.fromScriptPubKey(s, config.network);
|
// console.log('[TransactionDb.js.518]', u.inspect(tx,{depth:10})); //TODO
|
||||||
|
// Input Outpoints (mark them as spent)
|
||||||
// support only for p2pubkey p2pubkeyhash and p2sh
|
for(var ii in tx.vin) {
|
||||||
if (addrs.length === 1) {
|
var i = tx.vin[ii];
|
||||||
tx.out[to].addrStr = addrs[0].toString();
|
if (i.txid){
|
||||||
tx.out[to].n = to;
|
var k = SPENT_PREFIX + i.txid + '-' + i.vout + '-' + txid + '-' + i.n;
|
||||||
}
|
dbScript.push({
|
||||||
to++;
|
type: 'put',
|
||||||
|
key: k,
|
||||||
|
value: ts || 0,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
var count = 0;
|
|
||||||
txInfo.vin = txInfo. in .map(function(txin) {
|
|
||||||
var i = {};
|
|
||||||
|
|
||||||
if (txin.coinbase) {
|
|
||||||
txInfo.isCoinBase = true;
|
|
||||||
} else {
|
|
||||||
i.txid = txin.prev_out.hash;
|
|
||||||
i.vout = txin.prev_out.n;
|
|
||||||
}
|
}
|
||||||
i.n = count++;
|
|
||||||
return 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);
|
||||||
|
|
||||||
|
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,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
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;
|
}
|
||||||
});
|
tx.relatedAddrs=relatedAddrs;
|
||||||
|
return dbScript;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
TransactionDb.prototype.add = function(tx, blockhash, cb) {
|
TransactionDb.prototype.add = function(tx, blockhash, cb) {
|
||||||
var self = this;
|
var dbScript = this._addScript(tx, blockhash);
|
||||||
var addrs = [];
|
db.batch(dbScript, cb);
|
||||||
|
};
|
||||||
|
|
||||||
if (tx.hash) self.adaptTxObject(tx);
|
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);
|
||||||
|
};
|
||||||
|
|
||||||
var ts = tx.time;
|
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();
|
||||||
|
|
||||||
async.series([
|
Rpc.getTxInfo(tx, function(err, inInfo) {
|
||||||
// Input Outpoints (mark them as spent)
|
if (!inInfo) return each_cb(err);
|
||||||
function(p_c) {
|
dbScript = dbScript.concat(self._addScript(inInfo));
|
||||||
if (tx.isCoinBase) return p_c();
|
return each_cb();
|
||||||
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) {
|
function(err) {
|
||||||
return p_c(err);
|
if (err) return next(err);
|
||||||
});
|
db.batch(dbScript,next);
|
||||||
},
|
|
||||||
// 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);
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
TransactionDb.prototype.addMany = function(txs, next) {
|
||||||
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();
|
if (!txs) return next();
|
||||||
|
|
||||||
async.forEachLimit(txs, CONCURRENCY, function(t, each_cb) {
|
var fn = (typeof txs[0] ==='string') ?
|
||||||
if (typeof t === 'string') {
|
this._addManyFromHashes : this._addManyFromObjs;
|
||||||
// TODO: parse it from networks.genesisTX?
|
|
||||||
if (t === genesisTXID) return each_cb();
|
|
||||||
|
|
||||||
Rpc.getTxInfo(t, function(err, inInfo) {
|
return fn.apply(this,[txs, next]);
|
||||||
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) {
|
TransactionDb.prototype.getPoolInfo = function(txid, cb) {
|
||||||
var self = this;
|
var self = this;
|
||||||
if (!b || !b.tx) return next();
|
|
||||||
|
|
||||||
return self.createFromArray(b.tx, b.hash, next);
|
Rpc.getTxInfo(txid, function(err, txInfo) {
|
||||||
|
if (err) return cb(false);
|
||||||
|
var ret;
|
||||||
|
|
||||||
|
if (txInfo && txInfo.isCoinBase)
|
||||||
|
ret = self.poolMatch.match(new Buffer(txInfo.vin[0].coinbase, 'hex'));
|
||||||
|
|
||||||
|
return cb(ret);
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = require('soop')(TransactionDb);
|
module.exports = require('soop')(TransactionDb);
|
||||||
|
|
|
@ -0,0 +1,5 @@
|
||||||
|
var winston = require('winston');
|
||||||
|
|
||||||
|
winston.info('starting...')
|
||||||
|
|
||||||
|
module.exports.logger=winston;
|
|
@ -1,7 +1,7 @@
|
||||||
{
|
{
|
||||||
"name": "insight-bitcore-api",
|
"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.",
|
"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": {
|
"author": {
|
||||||
"name": "Ryan X Charles",
|
"name": "Ryan X Charles",
|
||||||
"email": "ryan@bitpay.com"
|
"email": "ryan@bitpay.com"
|
||||||
|
@ -60,13 +60,13 @@
|
||||||
"soop": "=0.1.5",
|
"soop": "=0.1.5",
|
||||||
"commander": "*",
|
"commander": "*",
|
||||||
"bignum": "*",
|
"bignum": "*",
|
||||||
|
"winston": "*",
|
||||||
"express": "~3.4.7",
|
"express": "~3.4.7",
|
||||||
"buffertools": "*",
|
"buffertools": "*",
|
||||||
"should": "~2.1.1",
|
"should": "~2.1.1",
|
||||||
"socket.io": "~0.9.16",
|
"socket.io": "~0.9.16",
|
||||||
"moment": "~2.5.0",
|
"moment": "~2.5.0",
|
||||||
"sinon": "~1.7.3",
|
"sinon": "~1.7.3",
|
||||||
"chai": "~1.8.1",
|
|
||||||
"xmlhttprequest": "~1.6.0",
|
"xmlhttprequest": "~1.6.0",
|
||||||
"bufferput": "git://github.com/bitpay/node-bufferput.git"
|
"bufferput": "git://github.com/bitpay/node-bufferput.git"
|
||||||
},
|
},
|
||||||
|
@ -80,6 +80,7 @@
|
||||||
"grunt-nodemon": "~0.2.0",
|
"grunt-nodemon": "~0.2.0",
|
||||||
"grunt-mocha-test": "~0.8.1",
|
"grunt-mocha-test": "~0.8.1",
|
||||||
"should": "2.1.1",
|
"should": "2.1.1",
|
||||||
|
"chai": "=1.9.1",
|
||||||
"grunt-markdown": "~0.5.0"
|
"grunt-markdown": "~0.5.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,6 +5,7 @@ process.env.NODE_ENV = process.env.NODE_ENV || 'development';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var should = require('chai');
|
||||||
var assert = require('assert'),
|
var assert = require('assert'),
|
||||||
fs = require('fs'),
|
fs = require('fs'),
|
||||||
util = require('util'),
|
util = require('util'),
|
||||||
|
@ -29,10 +30,13 @@ describe('TransactionDb fromIdWithInfo', function(){
|
||||||
assert.equal(tx.txid, txid);
|
assert.equal(tx.txid, txid);
|
||||||
assert(!tx.info.isCoinBase);
|
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(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();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -134,7 +138,7 @@ describe('TransactionDb Outs', function(){
|
||||||
assert.equal(readItems.length,0);
|
assert.equal(readItems.length,0);
|
||||||
|
|
||||||
var unmatch=[];
|
var unmatch=[];
|
||||||
txDb.createFromArray([v.txid], null, function(err) {
|
txDb.addMany([v.txid], function(err) {
|
||||||
if (err) return done(err);
|
if (err) return done(err);
|
||||||
|
|
||||||
txDb.fromTxId( v.txid, function(err, readItems) {
|
txDb.fromTxId( v.txid, function(err, readItems) {
|
||||||
|
|
|
@ -27,7 +27,7 @@ describe('TransactionDb Expenses', function(){
|
||||||
function(txid,c_out) {
|
function(txid,c_out) {
|
||||||
async.each(spentValid[txid],
|
async.each(spentValid[txid],
|
||||||
function(i,c_in) {
|
function(i,c_in) {
|
||||||
txDb.createFromArray([i.txid], null, function(err) {
|
txDb.addMany([i.txid], function(err) {
|
||||||
return c_in();
|
return c_in();
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
|
@ -2,12 +2,12 @@
|
||||||
'use strict';
|
'use strict';
|
||||||
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
|
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
|
||||||
|
|
||||||
|
var should = require('chai');
|
||||||
|
|
||||||
var
|
var
|
||||||
assert = require('assert'),
|
assert = require('assert'),
|
||||||
async = require('async'),
|
async = require('async'),
|
||||||
HistoricSync = require('../../lib/HistoricSync').class();
|
HistoricSync = require('../../lib/HistoricSync');
|
||||||
|
|
||||||
|
|
||||||
var s;
|
var s;
|
||||||
var b = [
|
var b = [
|
||||||
|
@ -16,6 +16,7 @@ var b = [
|
||||||
'000000008d55c3e978639f70af1d2bf1fe6f09cb3143e104405a599215c89a48', //2
|
'000000008d55c3e978639f70af1d2bf1fe6f09cb3143e104405a599215c89a48', //2
|
||||||
'000000009b3bca4909f38313f2746120129cce4a699a1f552390955da470c5a9', //3
|
'000000009b3bca4909f38313f2746120129cce4a699a1f552390955da470c5a9', //3
|
||||||
'00000000ede57f31cc598dc241d129ccb4d8168ef112afbdc870dc60a85f5dd3', //4 B#20
|
'00000000ede57f31cc598dc241d129ccb4d8168ef112afbdc870dc60a85f5dd3', //4 B#20
|
||||||
|
'000000001a29aff8154de6230a4909a3a971c52ae590006e00fddff33f9e3773', //5 B#21
|
||||||
];
|
];
|
||||||
var t = [
|
var t = [
|
||||||
'd08582d3711f75d085c618874fb0d049ae09d5ec95ec6f5abd289f4b54712c54', // TX from B#16
|
'd08582d3711f75d085c618874fb0d049ae09d5ec95ec6f5abd289f4b54712c54', // TX from B#16
|
||||||
|
@ -25,7 +26,7 @@ var t = [
|
||||||
'd45f9da73619799e9d7bd03cc290e70875ea4cbad56b8bffa15135fbbb3df9ea', //4 Tx from B20
|
'd45f9da73619799e9d7bd03cc290e70875ea4cbad56b8bffa15135fbbb3df9ea', //4 Tx from B20
|
||||||
];
|
];
|
||||||
|
|
||||||
var test = function(cb) {
|
var initialTest = function(cb) {
|
||||||
async.each([2,3,4], function(i,c) {
|
async.each([2,3,4], function(i,c) {
|
||||||
s.sync.bDb.getPrev(b[i], function(err, p) {
|
s.sync.bDb.getPrev(b[i], function(err, p) {
|
||||||
assert.equal(p,b[i-1]);
|
assert.equal(p,b[i-1]);
|
||||||
|
@ -43,19 +44,37 @@ var test = function(cb) {
|
||||||
assert.equal(p,b[i+1]);
|
assert.equal(p,b[i+1]);
|
||||||
return c();
|
return c();
|
||||||
});
|
});
|
||||||
|
}, function() {
|
||||||
|
async.each([0,1,2,3], function(i,c) {
|
||||||
|
s.sync.bDb.getHeight(b[i], function(err, h) {
|
||||||
|
assert.equal(h,16+i);
|
||||||
|
return c();
|
||||||
|
});
|
||||||
|
}, function() {
|
||||||
|
async.each([0,1,2,3], function(i,c) {
|
||||||
|
s.sync.bDb.getDepth(b[i], function(err, d) {
|
||||||
|
assert.equal(d,4-i);
|
||||||
|
return c();
|
||||||
|
});
|
||||||
}, cb);
|
}, cb);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* TEST CASES
|
* TEST CASES
|
||||||
*
|
*
|
||||||
|
* b0 height = 16;
|
||||||
|
*
|
||||||
* Blocks: 0-1-2-3-4
|
* Blocks: 0-1-2-3-4
|
||||||
* case 1)
|
* case 1)
|
||||||
* 0-1-2-3-4
|
* 0-1-2-3-4
|
||||||
* \
|
* \
|
||||||
* C1*
|
* C1* (height should be 19)
|
||||||
*
|
*
|
||||||
* case 2)
|
* case 2)
|
||||||
* 0-1-2---3-4
|
* 0-1-2---3-4
|
||||||
|
@ -75,474 +94,473 @@ var test = function(cb) {
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
var checkTxs = function(txs,heights){
|
||||||
|
var i=0;
|
||||||
|
txs.forEach(function(tx){
|
||||||
|
var v=heights[i++];
|
||||||
|
it('tx height:'+tx+' #'+v,function(done){
|
||||||
|
s.sync.bDb.getBlockForTx(tx, function(err,hash,height) {
|
||||||
|
assert(!err,err);
|
||||||
|
if (v>=0) {
|
||||||
|
assert(hash);
|
||||||
|
height.should.equal(v);
|
||||||
|
} else {
|
||||||
|
assert(!hash);
|
||||||
|
assert(!height);
|
||||||
|
}
|
||||||
|
|
||||||
|
return done();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
//heights is optional
|
||||||
|
var checkBlocks = function(hashes,heights){
|
||||||
|
var i=0;
|
||||||
|
hashes.forEach(function(hash){
|
||||||
|
var v = heights[i++];
|
||||||
|
it('block height:'+hash+' #'+v,function(done){
|
||||||
|
s.sync.bDb.getHeight(hash, function(err,height) {
|
||||||
|
assert(!err,err);
|
||||||
|
height.should.equal(v);
|
||||||
|
return done();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
describe('Sync Reorgs', function(){
|
describe('Sync Reorgs', function(){
|
||||||
|
var opts = {
|
||||||
|
forceRPC: true,
|
||||||
|
stopAt: b[5],
|
||||||
|
};
|
||||||
|
|
||||||
before(function(done) {
|
before(function(done) {
|
||||||
s = new HistoricSync();
|
s = new HistoricSync();
|
||||||
s.init({}, function(err) {
|
|
||||||
if (err) return done(err);
|
|
||||||
s.sync.destroy(done);
|
s.sync.destroy(done);
|
||||||
});
|
});
|
||||||
});
|
|
||||||
|
|
||||||
it('simple RPC forward syncing', function(done) {
|
it('simple RPC forward syncing', function(done) {
|
||||||
s.getPrevNextBlock(s.genesis,b[4], {
|
s.start(opts, function(err) {
|
||||||
next: true,
|
|
||||||
}, function(err) {
|
|
||||||
if (err) return done(err);
|
if (err) return done(err);
|
||||||
test(done);
|
initialTest(done);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
var case1 = {
|
var case1 = {
|
||||||
hash: '0000000000000000000000000000000000000000000000000000000000000001',
|
hash: '0000000042d3db6c529dd8f1b085367cb6d907b534f5b1a5dfdd3a34a3459886',
|
||||||
tx: [ 'f0596531810160d090813673b4a397f4617aab44eb26c7f06c8a766eac984b91' ],
|
tx: [ '2dc27c8d4b98f5e2ed009cfc164ac4990f18e03c4d5b71e780f9c8b7b2c5f151' ],
|
||||||
time: 1296690099,
|
time: 1296690099,
|
||||||
previousblockhash: b[2],
|
previousblockhash: b[2],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
it('reorg, case 1', function(done) {
|
describe('reorg, case 1', function(done) {
|
||||||
async.series([
|
checkTxs([t[0], t[1], t[2], t[3], t[4]],[16,17,18,19,20]);
|
||||||
function (c) {
|
checkBlocks([b[0], b[1], b[2], b[3], b[4]],[16,17,18,19,20]);
|
||||||
s.sync.txDb.isConfirmed(t[0], function(err,is) {
|
it('trigger reorg case 1', function(done1){
|
||||||
assert(!err);
|
|
||||||
assert(is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(t[3], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(t[4], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.storeTipBlock(case1, function(err) {
|
s.sync.storeTipBlock(case1, function(err) {
|
||||||
assert(!err, 'shouldnt return error' + err);
|
assert(!err, 'shouldnt return error' + err);
|
||||||
return c();
|
done1();
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.bDb.isMain(b[2], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.bDb.isMain(b[3], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(!is, b[3] + 'should not be on main chain');
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.bDb.isMain(b[4], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(!is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(t[0], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(t[3], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(!is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(t[4], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(!is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(case1.tx[0], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
], done );
|
|
||||||
});
|
|
||||||
|
|
||||||
it('reorg, case 1 (repeat)', function(done) {
|
|
||||||
s.sync.storeTipBlock(case1, function(err) {
|
|
||||||
assert(!err, 'shouldnt return error' + err);
|
|
||||||
return done();
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
checkTxs([t[0], t[1], t[2], t[3], t[4],case1.tx],[16,17,18,-1,-1,19]);
|
||||||
var case2 = {
|
checkBlocks([b[0], b[1], b[2],b[3],b[4],case1.hash],[16,17,18,-1,-1,19]);
|
||||||
hash: '0000000000000000000000000000000000000000000000000000000000000002',
|
|
||||||
tx: [ '99bb359a4b12a588fcb9e59e5e8d92d593ce7a56d2ba42085fe86d9a0b4fde15' ],
|
|
||||||
time: 1296690099,
|
|
||||||
previousblockhash: b[3],
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
it('reorg, case 2', function(done) {
|
|
||||||
async.series([
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(t[0], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(case1.tx[0], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(t[4], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(!is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.storeTipBlock(case2, function(err) {
|
|
||||||
assert(!err, 'shouldnt return error' + err);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.bDb.isMain(b[3], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.bDb.isMain(b[4], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(!is, b[3] + 'should not be on main chain');
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.bDb.isMain(case1.hash, function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(!is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.bDb.isMain(case2.hash, function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(t[3], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is, 'transaction t[3] should be valid:' + t[3]);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(case1.tx[0], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(!is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(case2.tx[0], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(t[4], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(!is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.bDb.getNext(b[2], function(err, val) {
|
|
||||||
assert(!err);
|
|
||||||
assert.equal(val,b[3]);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
], done );
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
var case2b = {
|
|
||||||
hash: '0000000000000000000000000000000000000000000000000000000000000003',
|
|
||||||
tx: case1.tx,
|
|
||||||
time: 1296690099,
|
|
||||||
previousblockhash: case2.hash,
|
|
||||||
};
|
|
||||||
|
|
||||||
it('reorg, case 2b', function(done) {
|
|
||||||
async.series([
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(case2b.tx[0], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(!is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.storeTipBlock(case2b, function(err) {
|
|
||||||
assert(!err, 'shouldnt return error' + err);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(t[3], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is, 'transaction t[3] should be valid:' + t[3]);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(case2b.tx[0], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
], done );
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
var case2c = {
|
|
||||||
hash: '0000000000000000000000000000000000000000000000000000000000000004',
|
|
||||||
tx: case2.tx,
|
|
||||||
time: 1296690099,
|
|
||||||
previousblockhash: case1.hash,
|
|
||||||
};
|
|
||||||
|
|
||||||
it('reorg, case 2c', function(done) {
|
|
||||||
async.series([
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(case1.tx[0], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.bDb.isMain(case1.hash, function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(!is, 'case1 block shouldnt be main:' + case1.hash);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(case2c.tx[0], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is); //It was there before (from case2)
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.storeTipBlock(case2c, function(err) {
|
|
||||||
assert(!err, 'shouldnt return error' + err);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(case1.tx[0], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.bDb.has(case1.hash, function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.bDb.has(case2c.hash, function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(case2c.tx[0], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(t[3], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(!is, 'TX t[3]: shouldnt be confirmed:' + t[3] +':'+ is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(t[4], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(!is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(case2.tx[0], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
|
|
||||||
], done );
|
|
||||||
});
|
|
||||||
|
|
||||||
var case3 = {
|
|
||||||
hash: '0000000000000000000000000000000000000000000000000000000000000005',
|
|
||||||
tx: case2.tx,
|
|
||||||
time: 1296690099,
|
|
||||||
previousblockhash: '666',
|
|
||||||
};
|
|
||||||
|
|
||||||
it('reorg, case 3)', function(done) {
|
|
||||||
async.series([
|
|
||||||
function (c) {
|
|
||||||
s.sync.storeTipBlock(case3, function(err) {
|
|
||||||
assert(!err, 'shouldnt return error' + err);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
|
|
||||||
//shoudnt change anything
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(case1.tx[0], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.bDb.has(case1.hash, function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.bDb.has(case2c.hash, function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(case2c.tx[0], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(t[3], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(!is, 'TX t[3]: shouldnt be confirmed:' + t[3] +':'+ is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(t[4], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(!is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(case2.tx[0], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
|
|
||||||
], done );
|
|
||||||
});
|
|
||||||
|
|
||||||
var p2p = {
|
|
||||||
hash: '0000000000000000000000000000000000000000000000000000000000000006',
|
|
||||||
tx: ['f6c2901f39fd07f2f2e503183d76f73ecc1aee9ac9216fde58e867bc29ce674e'],
|
|
||||||
time: 1296690099,
|
|
||||||
previousblockhash: '111',
|
|
||||||
};
|
|
||||||
|
|
||||||
it('p2p, no reorg allowed', function(done) {
|
|
||||||
async.series([
|
|
||||||
function (c) {
|
|
||||||
s.sync.storeTipBlock(p2p, false, function(err) {
|
|
||||||
assert(!err, 'shouldnt return error' + err);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.bDb.has(p2p.hash, function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.txDb.isConfirmed(p2p.tx[0], function(err,is) {
|
|
||||||
assert(!err);
|
|
||||||
assert(is);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.bDb.getNext(p2p.hash, function(err,v) {
|
|
||||||
assert(!err);
|
|
||||||
assert.equal(v,p2p.nextblockhash);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function (c) {
|
|
||||||
s.sync.bDb.getNext(p2p.previousblockhash, function(err,v) {
|
|
||||||
assert(!err);
|
|
||||||
assert.equal(v,p2p.hash);
|
|
||||||
return c();
|
|
||||||
});
|
|
||||||
},
|
|
||||||
|
|
||||||
], done );
|
|
||||||
});
|
});
|
||||||
|
//
|
||||||
|
// it('reorg, case 1 (repeat)', function(done) {
|
||||||
|
// s.sync.storeTipBlock(case1, function(err) {
|
||||||
|
// assert(!err, 'shouldnt return error' + err);
|
||||||
|
// return done();
|
||||||
|
// });
|
||||||
|
// });
|
||||||
|
//
|
||||||
|
// var case2 = {
|
||||||
|
// hash: '00000000c262f9428bb84407780bb0bd008b74941d651111ab2500cf649fa45d',
|
||||||
|
// tx: [ '3fa6fce216e91c9dc9a6267168e9d8bfb4ae57aec0d26590442cfec6e8233682' ],
|
||||||
|
// time: 1296690099,
|
||||||
|
// previousblockhash: b[3],
|
||||||
|
// };
|
||||||
|
//
|
||||||
|
//
|
||||||
|
// it('reorg, case 2', function(done) {
|
||||||
|
// async.series([
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.txDb.getBlock(t[0], function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.txDb.getBlock(case1.tx[0], function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.txDb.getBlock(t[4], function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(!is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// // BEFORE
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.bDb.getHeight(b[3], function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert.equal(is,-1);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.storeTipBlock(case2, function(err) {
|
||||||
|
// assert(!err, 'shouldnt return error' + err);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// // AFTER
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.bDb.getHeight(b[3], function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert.equal(is,19);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.bDb.getHeight(b[4], function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert.equal( is,-1, b[3] + 'should not be on main chain: #'+is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.bDb.getHeight(case1.hash, function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert.equal(is,-1);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.bDb.getHeight(case2.hash, function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert.equal(is, 20);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.txDb.getBlock(t[3], function(err,is) {
|
||||||
|
// console.log('[99-sync.js.descructive-test.300:is:]',is); //TODO
|
||||||
|
// assert(!err);
|
||||||
|
// assert(is, 'transaction t[3] should be valid:' + t[3]);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.txDb.getBlock(case1.tx[0], function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(!is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.txDb.getBlock(case2.tx[0], function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.txDb.getBlock(t[4], function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(!is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.bDb.getNext(b[2], function(err, val) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert.equal(val,b[3]);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
//
|
||||||
|
//
|
||||||
|
//
|
||||||
|
// ], done );
|
||||||
|
// });
|
||||||
|
//
|
||||||
|
//
|
||||||
|
// var case2b = {
|
||||||
|
// hash: '0000000022bb34bc09f8d8d0ae26b86c87f8483e54b9c3addfe6f30b12bc656a',
|
||||||
|
// tx: case1.tx,
|
||||||
|
// time: 1296690099,
|
||||||
|
// previousblockhash: case2.hash,
|
||||||
|
// };
|
||||||
|
//
|
||||||
|
// it('reorg, case 2b', function(done) {
|
||||||
|
// async.series([
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.txDb.getBlock(case2b.tx[0], function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(!is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.storeTipBlock(case2b, function(err) {
|
||||||
|
// assert(!err, 'shouldnt return error' + err);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.txDb.getBlock(t[3], function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(is, 'transaction t[3] should be valid:' + t[3]);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.txDb.getBlock(case2b.tx[0], function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// ], done );
|
||||||
|
// });
|
||||||
|
//
|
||||||
|
//
|
||||||
|
//
|
||||||
|
// var case2c = {
|
||||||
|
// hash: '0000000000000000000000000000000000000000000000000000000000000004',
|
||||||
|
// tx: case2.tx,
|
||||||
|
// time: 1296690099,
|
||||||
|
// previousblockhash: case1.hash,
|
||||||
|
// };
|
||||||
|
//
|
||||||
|
// it('reorg, case 2c', function(done) {
|
||||||
|
// async.series([
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.txDb.getBlock(case1.tx[0], function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.bDb.getHeight(case1.hash, function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert.equal(is, -1, 'case1 block shouldnt be main:' + case1.hash);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.txDb.getBlock(case2c.tx[0], function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(is); //It was there before (from case2)
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.storeTipBlock(case2c, function(err) {
|
||||||
|
// assert(!err, 'shouldnt return error' + err);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.txDb.getBlock(case1.tx[0], function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.bDb.has(case1.hash, function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.bDb.has(case2c.hash, function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.bDb.getHeight(case1.hash, function(err,h) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert.equal(h,19);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.bDb.getHeight(case2c.hash, function(err,h) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert.equal(h,20);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.txDb.getBlock(case2c.tx[0], function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.txDb.getBlock(t[3], function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(!is, 'TX t[3]: shouldnt be confirmed:' + t[3] +':'+ is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.txDb.getBlock(t[4], function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(!is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.txDb.getBlock(case2.tx[0], function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
//
|
||||||
|
// ], done );
|
||||||
|
// });
|
||||||
|
//
|
||||||
|
// var case3 = {
|
||||||
|
// hash: '0000000000000000000000000000000000000000000000000000000000000005',
|
||||||
|
// tx: case2.tx,
|
||||||
|
// time: 1296690099,
|
||||||
|
// previousblockhash: '666',
|
||||||
|
// };
|
||||||
|
//
|
||||||
|
// it('reorg, case 3)', function(done) {
|
||||||
|
// async.series([
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.storeTipBlock(case3, function(err) {
|
||||||
|
// assert(err, 'should return error' + err);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
//
|
||||||
|
// //shoudnt change anything
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.txDb.getBlock(case1.tx[0], function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.bDb.has(case1.hash, function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.bDb.has(case2c.hash, function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.txDb.getBlock(case2c.tx[0], function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.txDb.getBlock(t[3], function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(!is, 'TX t[3]: shouldnt be confirmed:' + t[3] +':'+ is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.txDb.getBlock(t[4], function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(!is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.txDb.getBlock(case2.tx[0], function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
//
|
||||||
|
// ], done );
|
||||||
|
// });
|
||||||
|
//
|
||||||
|
// var p2p = {
|
||||||
|
// hash: '0000000000000000000000000000000000000000000000000000000000000006',
|
||||||
|
// tx: ['f6c2901f39fd07f2f2e503183d76f73ecc1aee9ac9216fde58e867bc29ce674e'],
|
||||||
|
// time: 1296690099,
|
||||||
|
// previousblockhash: '111',
|
||||||
|
// };
|
||||||
|
//
|
||||||
|
// it('p2p, no reorg allowed', function(done) {
|
||||||
|
// async.series([
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.storeTipBlock(p2p, false, function(err) {
|
||||||
|
// assert(!err, 'shouldnt return error' + err);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.bDb.has(p2p.hash, function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.txDb.getBlock(p2p.tx[0], function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert(is);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.bDb.getNext(p2p.hash, function(err,v) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert.equal(v,p2p.nextblockhash);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.bDb.getNext(p2p.previousblockhash, function(err,v) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert.equal(v,p2p.hash);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
// function (c) {
|
||||||
|
// s.sync.bDb.getHeight(p2p.hash, function(err,is) {
|
||||||
|
// assert(!err);
|
||||||
|
// assert.equal(is,-1);
|
||||||
|
// return c();
|
||||||
|
// });
|
||||||
|
// },
|
||||||
|
//
|
||||||
|
// ], done );
|
||||||
|
// });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -11,8 +11,11 @@ var assert = require('assert'),
|
||||||
addrValid = JSON.parse(fs.readFileSync('test/integration/addr.json')),
|
addrValid = JSON.parse(fs.readFileSync('test/integration/addr.json')),
|
||||||
utxoValid = JSON.parse(fs.readFileSync('test/integration/utxo.json'));
|
utxoValid = JSON.parse(fs.readFileSync('test/integration/utxo.json'));
|
||||||
|
|
||||||
|
var should = require('chai');
|
||||||
|
|
||||||
var txDb;
|
var txDb;
|
||||||
describe('Address balances', function() {
|
describe('Address balances', function() {
|
||||||
|
this.timeout(5000);
|
||||||
|
|
||||||
before(function(c) {
|
before(function(c) {
|
||||||
txDb = TransactionDb;
|
txDb = TransactionDb;
|
||||||
|
@ -24,18 +27,16 @@ describe('Address balances', function() {
|
||||||
console.log(v.addr + ' => disabled in JSON');
|
console.log(v.addr + ' => disabled in JSON');
|
||||||
} else {
|
} else {
|
||||||
it('Address info for: ' + v.addr, function(done) {
|
it('Address info for: ' + v.addr, function(done) {
|
||||||
this.timeout(5000);
|
|
||||||
|
|
||||||
var a = new Address(v.addr, txDb);
|
var a = new Address(v.addr, txDb);
|
||||||
|
|
||||||
a.update(function(err) {
|
a.update(function(err) {
|
||||||
if (err) done(err);
|
if (err) done(err);
|
||||||
assert.equal(v.addr, a.addrStr);
|
v.addr.should.equal(a.addrStr);
|
||||||
assert.equal(a.unconfirmedTxApperances ,v.unconfirmedTxApperances || 0, 'unconfirmedTxApperances');
|
a.unconfirmedTxApperances.should.equal(v.unconfirmedTxApperances || 0, 'unconfirmedTxApperances');
|
||||||
assert.equal(a.unconfirmedBalanceSat ,v.unconfirmedBalanceSat || 0, 'unconfirmedBalanceSat: ' + a.unconfirmedBalanceSat + ' vs.: ' + v.unconfirmedBalanceSat );
|
a.unconfirmedBalanceSat.should.equal(v.unconfirmedBalanceSat || 0, 'unconfirmedBalanceSat');
|
||||||
if (v.txApperances)
|
if (v.txApperances)
|
||||||
assert.equal(v.txApperances, a.txApperances, 'txApperances: ' + a.txApperances);
|
a.txApperances.should.equal(v.txApperances, 'txApperances');
|
||||||
if (v.totalReceived) assert.equal(v.totalReceived, a.totalReceived, 'received: ' + a.totalReceived);
|
|
||||||
|
if (v.totalReceived) a.totalReceived.should.equal(v.totalReceived,'totalReceived');
|
||||||
if (v.totalSent) assert.equal(v.totalSent, a.totalSent, 'send: ' + a.totalSent);
|
if (v.totalSent) assert.equal(v.totalSent, a.totalSent, 'send: ' + a.totalSent);
|
||||||
|
|
||||||
if (v.balance) assert.equal(v.balance, a.balance, 'balance: ' + a.balance);
|
if (v.balance) assert.equal(v.balance, a.balance, 'balance: ' + a.balance);
|
||||||
|
@ -49,30 +50,137 @@ describe('Address balances', function() {
|
||||||
done();
|
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() {
|
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) {
|
utxoValid.forEach(function(v) {
|
||||||
if (v.disabled) {
|
if (v.disabled) {
|
||||||
console.log(v.addr + ' => disabled in JSON');
|
console.log(v.addr + ' => disabled in JSON');
|
||||||
} else {
|
} else {
|
||||||
it('Address utxo for: ' + v.addr, function(done) {
|
it('Address utxo for: ' + v.addr, function(done) {
|
||||||
this.timeout(50000);
|
this.timeout(2000);
|
||||||
|
|
||||||
var a = new Address(v.addr, txDb);
|
var a = new Address(v.addr, txDb);
|
||||||
a.getUtxo(function(err, utxo) {
|
a.getUtxo(function(err, utxo) {
|
||||||
if (err) done(err);
|
if (err) done(err);
|
||||||
assert.equal(v.addr, a.addrStr);
|
assert.equal(v.addr, a.addrStr);
|
||||||
if (v.length) assert.equal(v.length, utxo.length, 'length: ' + utxo.length);
|
if (v.length) utxo.length.should.equal(v.length, 'Unspent count');
|
||||||
if (v.tx0id) assert.equal(v.tx0id, utxo[0].txid, 'have tx: ' + utxo[0].txid);
|
if (v.tx0id) {
|
||||||
if (v.tx0scriptPubKey)
|
var x=utxo.filter(function(x){
|
||||||
assert.equal(v.tx0scriptPubKey, utxo[0].scriptPubKey, 'have tx: ' + utxo[0].scriptPubKey);
|
return x.txid === v.tx0id;
|
||||||
if (v.tx0amount)
|
});
|
||||||
assert.equal(v.tx0amount, utxo[0].amount, 'amount: ' + utxo[0].amount);
|
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();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
@ -41,35 +41,36 @@
|
||||||
"totalReceived": 54.81284116
|
"totalReceived": 54.81284116
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
"disabled": 1,
|
||||||
"addr": "mzW2hdZN2um7WBvTDerdahKqRgj3md9C29",
|
"addr": "mzW2hdZN2um7WBvTDerdahKqRgj3md9C29",
|
||||||
"balance": 1271.87752288,
|
"balance": 1363.14677867,
|
||||||
"totalReceived": 1271.87752288,
|
"totalReceived": 1363.14677867,
|
||||||
"totalSent": 0,
|
"totalSent": 0,
|
||||||
"txApperances": 6197,
|
"txApperances": 7947,
|
||||||
"unconfirmedTxApperances": 3,
|
"unconfirmedTxApperances": 5,
|
||||||
"unconfirmedBalanceSat": 149174913
|
"unconfirmedBalanceSat": 149174913
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"addr": "mjRmkmYzvZN3cA3aBKJgYJ65epn3WCG84H",
|
"addr": "mjRmkmYzvZN3cA3aBKJgYJ65epn3WCG84H",
|
||||||
"txApperances": 7164,
|
"txApperances": 7166,
|
||||||
"balance": 46413.0,
|
"balance": 6513,
|
||||||
"totalReceived": 357130.17644359,
|
"totalReceived": 357130.17644359,
|
||||||
"totalSent": 310717.17644359
|
"totalSent": 350617.17644359
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"addr": "mgKY35SXqxFpcKK3Dq9mW9919N7wYXvcFM",
|
"addr": "mgKY35SXqxFpcKK3Dq9mW9919N7wYXvcFM",
|
||||||
"txApperances": 1,
|
"txApperances": 2,
|
||||||
"balance": 0.01979459,
|
"balance": 0,
|
||||||
"totalReceived": 0.01979459,
|
"totalReceived": 0.01979459,
|
||||||
"totalSent": 0,
|
"totalSent": 0,
|
||||||
"transactions": [ "91800d80bb4c69b238c9bfd94eb5155ab821e6b25cae5c79903d12853bbb4ed5" ]
|
"transactions": [ "91800d80bb4c69b238c9bfd94eb5155ab821e6b25cae5c79903d12853bbb4ed5" ]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"addr": "mmvP3mTe53qxHdPqXEvdu8WdC7GfQ2vmx5",
|
"addr": "mmvP3mTe53qxHdPqXEvdu8WdC7GfQ2vmx5",
|
||||||
"balance": 10580.50027254,
|
"balance": 5524.61806422,
|
||||||
"totalReceived": 12157.65075053,
|
"totalReceived": 12157.65075053,
|
||||||
"totalSent": 1577.15047799,
|
"totalSent": 6633.03268631,
|
||||||
"txApperances": 441,
|
"txApperances": 443,
|
||||||
"transactions": [
|
"transactions": [
|
||||||
"91800d80bb4c69b238c9bfd94eb5155ab821e6b25cae5c79903d12853bbb4ed5",
|
"91800d80bb4c69b238c9bfd94eb5155ab821e6b25cae5c79903d12853bbb4ed5",
|
||||||
"f6e80d4fd1a2377406856c67d0cee5ac7e5120993ff97e617ca9aac33b4c6b1e",
|
"f6e80d4fd1a2377406856c67d0cee5ac7e5120993ff97e617ca9aac33b4c6b1e",
|
||||||
|
|
|
@ -7,10 +7,10 @@
|
||||||
"tx0amount": 0.38571339
|
"tx0amount": 0.38571339
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"addr": "mgKY35SXqxFpcKK3Dq9mW9919N7wYXvcFM",
|
"addr": "2N1pLkosf6o8Ciqs573iwwgVpuFS6NbNKx5",
|
||||||
"length": 1,
|
"length": 13,
|
||||||
"tx0id": "91800d80bb4c69b238c9bfd94eb5155ab821e6b25cae5c79903d12853bbb4ed5",
|
"tx0id": "b9cc61b55814a0f972788e9025db1013157f83716e08239026a156efe892a05c",
|
||||||
"tx0scriptPubKey": "76a91408cf4ceb2b7278043fcc7f545e6e6e73ef9a644f88ac",
|
"tx0scriptPubKey": "a9145e0461e38796367580305e3615fc1b70e4c3307687",
|
||||||
"tx0amount": 0.01979459
|
"tx0amount": 0.001
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|
|
@ -15,6 +15,7 @@ program
|
||||||
.option('-D --destroy', 'Remove current DB (and start from there)', 0)
|
.option('-D --destroy', 'Remove current DB (and start from there)', 0)
|
||||||
.option('-S --startfile', 'Number of file from bitcoind to start(default=0)')
|
.option('-S --startfile', 'Number of file from bitcoind to start(default=0)')
|
||||||
.option('-R --rpc', 'Force sync with RPC')
|
.option('-R --rpc', 'Force sync with RPC')
|
||||||
|
.option('--stop [hash]', 'StopAt block',1)
|
||||||
.option('-v --verbose', 'Verbose 0/1', 0)
|
.option('-v --verbose', 'Verbose 0/1', 0)
|
||||||
.parse(process.argv);
|
.parse(process.argv);
|
||||||
|
|
||||||
|
@ -30,10 +31,13 @@ async.series([
|
||||||
historicSync.sync.destroy(cb);
|
historicSync.sync.destroy(cb);
|
||||||
},
|
},
|
||||||
function(cb) {
|
function(cb) {
|
||||||
historicSync.start({
|
var opts= {
|
||||||
forceStartFile: program.startfile,
|
forceStartFile: program.startfile,
|
||||||
forceRPC: program.rpc,
|
forceRPC: program.rpc,
|
||||||
},cb);
|
stopAt: program.stop,
|
||||||
|
};
|
||||||
|
console.log('[options]',opts); //TODO
|
||||||
|
historicSync.start(opts,cb);
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
function(err) {
|
function(err) {
|
||||||
|
|
Loading…
Reference in New Issue