add MessageDb

This commit is contained in:
Manuel Araoz 2014-07-29 17:28:15 -03:00
parent 1c6010ba99
commit c39749c58e
7 changed files with 264 additions and 178 deletions

View File

@ -76,45 +76,6 @@ var bitcoindConf = {
disableAgent: true disableAgent: true
}; };
/*jshint multistr: true */
console.log(
'\n\
____ _ __ __ ___ _ \n\
/ _/___ _____(_)___ _/ /_ / /_ / | ____ (_)\n\
/ // __ \\/ ___/ / __ `/ __ \\/ __/ / /\| \| / __ \\/ / \n\
_/ // / / (__ ) / /_/ / / / / /_ / ___ |/ /_/ / / \n\
/___/_/ /_/____/_/\\__, /_/ /_/\\__/ /_/ |_/ .___/_/ \n\
/____/ /_/ \n\
\n\t\t\t\t\t\tv%s\n\
# Configuration:\n\
\t\tNetwork: %s\tINSIGHT_NETWORK\n\
\t\tDatabase Path: %s\tINSIGHT_DB\n\
\t\tSafe Confirmations: %s\tINSIGHT_SAFE_CONFIRMATIONS\n\
\t\tIgnore Cache: %s\tINSIGHT_IGNORE_CACHE\n\
# Bicoind Connection configuration:\n\
\t\tRPC Username: %s\tBITCOIND_USER\n\
\t\tRPC Password: %s\tBITCOIND_PASS\n\
\t\tRPC Protocol: %s\tBITCOIND_PROTO\n\
\t\tRPC Host: %s\tBITCOIND_HOST\n\
\t\tRPC Port: %s\tBITCOIND_PORT\n\
\t\tP2P Host: %s\tBITCOIND_P2P_HOST\n\
\t\tP2P Port: %s\tBITCOIND_P2P_PORT\n\
\t\tData Dir: %s\tBITCOIND_DATADIR\n\
\t\t%s\n\
\nChange setting by assigning the enviroment variables in the last column. Example:\n\
$ INSIGHT_NETWORK="testnet" BITCOIND_HOST="123.123.123.123" ./insight.js\
\n\n',
version,
network, home, safeConfirmations, ignoreCache ? 'yes' : 'no',
bitcoindConf.user,
bitcoindConf.pass ? 'Yes(hidden)' : 'No',
bitcoindConf.protocol,
bitcoindConf.host,
bitcoindConf.port,
bitcoindConf.p2pHost,
bitcoindConf.p2pPort,
dataDir + (network === 'testnet' ? '*' : ''), (network === 'testnet' ? '* (/testnet3 is added automatically)' : '')
);
if (!fs.existsSync(db)) { if (!fs.existsSync(db)) {

View File

@ -15,6 +15,45 @@ var express = require('express'),
//Initializing system variables //Initializing system variables
var config = require('./config/config'); var config = require('./config/config');
// text title
/*jshint multistr: true */
console.log(
'\n\
____ _ __ __ ___ _ \n\
/ _/___ _____(_)___ _/ /_ / /_ / | ____ (_)\n\
/ // __ \\/ ___/ / __ `/ __ \\/ __/ / /\| \| / __ \\/ / \n\
_/ // / / (__ ) / /_/ / / / / /_ / ___ |/ /_/ / / \n\
/___/_/ /_/____/_/\\__, /_/ /_/\\__/ /_/ |_/ .___/_/ \n\
/____/ /_/ \n\
\n\t\t\t\t\t\tv%s\n\
# Configuration:\n\
\t\tNetwork: %s\tINSIGHT_NETWORK\n\
\t\tDatabase Path: %s\tINSIGHT_DB\n\
\t\tSafe Confirmations: %s\tINSIGHT_SAFE_CONFIRMATIONS\n\
\t\tIgnore Cache: %s\tINSIGHT_IGNORE_CACHE\n\
# Bicoind Connection configuration:\n\
\t\tRPC Username: %s\tBITCOIND_USER\n\
\t\tRPC Password: %s\tBITCOIND_PASS\n\
\t\tRPC Protocol: %s\tBITCOIND_PROTO\n\
\t\tRPC Host: %s\tBITCOIND_HOST\n\
\t\tRPC Port: %s\tBITCOIND_PORT\n\
\t\tP2P Port: %s\tBITCOIND_P2P_PORT\n\
\t\tData Dir: %s\tBITCOIND_DATADIR\n\
\t\t%s\n\
\nChange setting by assigning the enviroment variables in the last column. Example:\n\
$ INSIGHT_NETWORK="testnet" BITCOIND_HOST="123.123.123.123" ./insight.js\
\n\n',
version,
network, home, safeConfirmations, ignoreCache ? 'yes' : 'no',
bitcoindConf.user,
bitcoindConf.pass ? 'Yes(hidden)' : 'No',
bitcoindConf.protocol,
bitcoindConf.host,
bitcoindConf.port,
bitcoindConf.p2pPort,
dataDir + (network === 'testnet' ? '*' : ''), (network === 'testnet' ? '* (/testnet3 is added automatically)' : '')
);
/** /**
* express app * express app
*/ */
@ -32,8 +71,7 @@ var walk = function(path) {
if (/(.*)\.(js$)/.test(file)) { if (/(.*)\.(js$)/.test(file)) {
require(newPath); require(newPath);
} }
} } else if (stat.isDirectory()) {
else if (stat.isDirectory()) {
walk(newPath); walk(newPath);
} }
}); });
@ -45,7 +83,9 @@ walk(models_path);
* p2pSync process * p2pSync process
*/ */
var peerSync = new PeerSync({shouldBroadcast: true}); var peerSync = new PeerSync({
shouldBroadcast: true
});
if (!config.disableP2pSync) { if (!config.disableP2pSync) {
peerSync.run(); peerSync.run();
@ -67,8 +107,7 @@ if (!config.disableHistoricSync) {
} }
if (peerSync) peerSync.allowReorgs = true; if (peerSync) peerSync.allowReorgs = true;
}); });
} } else
else
if (peerSync) peerSync.allowReorgs = true; if (peerSync) peerSync.allowReorgs = true;

57
lib/MessageDb.js Normal file
View File

@ -0,0 +1,57 @@
'use strict';
var imports = require('soop').imports();
var levelup = require('levelup');
var config = require('../config/config');
var Rpc = imports.rpc || require('./Rpc');
var async = require('async');
var logger = require('./logger').logger;
var MESSAGE_PREFIX = 'msg-'; // msg-<sin1>-<sin2> => <message>
var MAX_OPEN_FILES = 500;
var CONCURRENCY = 5;
var db = imports.db || levelup(config.leveldb + '/messages', {
maxOpenFiles: MAX_OPEN_FILES
});
var d = logger.log;
var info = logger.info;
var MessageDb = function() {
db.on('put', function(key, value) {
console.log(key + '=>' + value);
});
db.on('ready', function() {
console.log('Database ready!');
});
};
MessageDb.prototype.close = function(cb) {
db.close(cb);
};
var messageKey = function(from, to, ts) {
if (!ts) ts = Math.round(new Date().getTime() / 1000);
return MESSAGE_PREFIX + from.toString() + '-' + to.toString() + '-' + ts;
};
MessageDb.prototype.addMessage = function(m, from, to, cb) {
var key = messageKey(from, to);
var value = m;
db.put(key, value, cb);
};
MessageDb.prototype.getMessages = function(from, to, from_ts, to_ts, cb) {
// TODO
db.get(messageKey(from, to), function(err, val) {
if (err && err.notFound) return cb();
if (err) return cb(err);
return cb(null, val);
});
};
module.exports = require('soop')(MessageDb);

View File

@ -42,7 +42,9 @@ var bitcore = require('bitcore'),
var logger = require('./logger').logger; var logger = require('./logger').logger;
var inf = logger.info; var inf = 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 PoolMatch = imports.poolMatch || require('soop').load('./PoolMatch', config); var PoolMatch = imports.poolMatch || require('soop').load('./PoolMatch', config);
// This is 0.1.2 = > c++ version of base58-native // This is 0.1.2 = > c++ version of base58-native
var base58 = require('base58-native').base58Check; var base58 = require('base58-native').base58Check;
@ -76,7 +78,9 @@ TransactionDb.prototype.drop = function(cb) {
var path = config.leveldb + '/txs'; var path = config.leveldb + '/txs';
db.close(function() { db.close(function() {
require('leveldown').destroy(path, function() { require('leveldown').destroy(path, function() {
db = levelup(path, {maxOpenFiles: 500}); db = levelup(path, {
maxOpenFiles: 500
});
return cb(); return cb();
}); });
}); });
@ -282,9 +286,10 @@ TransactionDb.prototype.fromTxIdN = function(txid, n, cb) {
if (!val || (err && err.notFound)) { if (!val || (err && err.notFound)) {
err = null; err = null;
ret= { unconfirmedInput: 1 }; ret = {
} unconfirmedInput: 1
else { };
} else {
var a = val.split(':'); var a = val.split(':');
ret = { ret = {
addr: a[0], addr: a[0],
@ -354,8 +359,7 @@ TransactionDb.prototype.cacheConfirmations = function(txouts,cb) {
// if spent, we overwrite scriptPubKey cache (not needed anymore) // if spent, we overwrite scriptPubKey cache (not needed anymore)
// First 1 = txout.isConfirmedCached (must be equal to 1 at this point) // First 1 = txout.isConfirmedCached (must be equal to 1 at this point)
infoToCache = [1, 1, txout.spentTxId, txout.spentIndex, txout.spentTs]; infoToCache = [1, 1, txout.spentTxId, txout.spentIndex, txout.spentTs];
} } else {
else {
if (!txout.isConfirmedCached) { if (!txout.isConfirmedCached) {
infoToCache.push(1); infoToCache.push(1);
txout.confirmedWillBeCached = 1; txout.confirmedWillBeCached = 1;
@ -391,8 +395,7 @@ TransactionDb.prototype.cacheScriptPubKey = function(txouts,cb) {
} }
if (txout.scriptPubKey) { if (txout.scriptPubKey) {
var infoToCache = [txout.value_sat, var infoToCache = [txout.value_sat, (txout.isConfirmedCached || txout.confirmedWillBeCached) ? 1 : 0, txout.scriptPubKey];
(txout.isConfirmedCached || txout.confirmedWillBeCached)?1:0, txout.scriptPubKey];
dbScript.push({ dbScript.push({
type: 'put', type: 'put',
key: txout.key, key: txout.key,
@ -469,7 +472,9 @@ TransactionDb.prototype.fromAddr = function(addr, opts, cb) {
}) })
.on('error', cb) .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.filter(function(x) {
return !x.spentIsConfirmed;
}), 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,
@ -499,7 +504,9 @@ TransactionDb.prototype.getStandardizedTx = function (tx, time, isCoinBase) {
var ti = 0; var ti = 0;
tx.vin = tx.ins.map(function(txin) { tx.vin = tx.ins.map(function(txin) {
var ret = {n: ti++}; var ret = {
n: ti++
};
if (isCoinBase) { if (isCoinBase) {
ret.isCoinBase = true; ret.isCoinBase = true;
} else { } else {
@ -517,7 +524,9 @@ TransactionDb.prototype.getStandardizedTx = function (tx, time, isCoinBase) {
var addrs = new Address.fromScriptPubKey(s, config.network); var addrs = new Address.fromScriptPubKey(s, config.network);
// support only for p2pubkey p2pubkeyhash and p2sh // support only for p2pubkey p2pubkeyhash and p2sh
if (addrs && addrs.length === 1) { if (addrs && addrs.length === 1) {
val = {addresses: [addrs[0].toString() ] }; val = {
addresses: [addrs[0].toString()]
};
} }
} }
return { return {
@ -548,6 +557,7 @@ TransactionDb.prototype.fillScriptPubKey = function(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 + '-',
@ -626,7 +636,9 @@ TransactionDb.prototype._addScript = function(tx, relatedAddrs) {
TransactionDb.prototype.add = function(tx, cb) { TransactionDb.prototype.add = function(tx, cb) {
var relatedAddrs = {}; var relatedAddrs = {};
var dbScript = this._addScript(tx, relatedAddrs); var dbScript = this._addScript(tx, relatedAddrs);
db.batch(dbScript, function(err) { return cb(err,relatedAddrs);}); db.batch(dbScript, function(err) {
return cb(err, relatedAddrs);
});
}; };
TransactionDb.prototype._addManyFromObjs = function(txs, next) { TransactionDb.prototype._addManyFromObjs = function(txs, next) {
@ -714,8 +726,7 @@ TransactionDb.prototype.migrateV02 = function(cb) {
var v = data.value.split(':'); var v = data.value.split(':');
dbScript.push({ dbScript.push({
type: 'put', type: 'put',
key: ADDR_PREFIX + k[1] + '-' + (END_OF_WORLD_TS - parseInt(v[1])) key: ADDR_PREFIX + k[1] + '-' + (END_OF_WORLD_TS - parseInt(v[1])) + '-' + k[2] + '-' + k[3],
+ '-' + k[2] + '-' + k[3],
value: v[0], value: v[0],
}); });
if (c++ > N) { if (c++ > N) {

View File

@ -80,7 +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", "chai": "*",
"grunt-markdown": "~0.5.0" "grunt-markdown": "~0.5.0"
} }
} }

View File

@ -28,8 +28,7 @@ describe('PeerSync', function() {
it('should return with no errors', function() { it('should return with no errors', function() {
expect(function() { expect(function() {
ps.handleInv(inv_info); ps.handleInv(inv_info);
}).not.to. }).not.to.throw(Error);
throw (Error);
}); });
it('should call sendGetData', function() { it('should call sendGetData', function() {
ps.handleInv(inv_info); ps.handleInv(inv_info);

19
test/test.MessageDb.js Normal file
View File

@ -0,0 +1,19 @@
'use strict';
var chai = require('chai');
var should = chai.should;
var MessageDb = require('../lib/MessageDb');
describe('MessageDb', function() {
it('should be able to create instance', function() {
var mdb = new MessageDb();
});
it('should receive events', function(done) {
var mdb = new MessageDb();
var message = {};
mdb.addMessage(message, 'from', 'to', function(err) {
done();
});
});
});