block syncing working!

This commit is contained in:
Matias Alejo Garcia 2014-01-06 23:50:29 -03:00
parent 1c96756743
commit e79e81fe4b
3 changed files with 134 additions and 1 deletions

68
app/models/Block.js Normal file
View File

@ -0,0 +1,68 @@
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Block Schema
*/
var BlockSchema = new Schema({
hash: {
type: String,
index: true,
unique: true,
},
size: Number,
confirmations: Number,
version: Number,
merkleroot: String,
tx: [ String ],
time: Date,
nonce: Number,
bits: String,
difficulty: Number,
chainwork: String,
previousblockhash: {
type: String,
index: true,
unique: true,
},
nextblockhash: {
type: String,
index: true,
unique: true,
},
});
/**
* Validations
*/
/*
BlockSchema.path('title').validate(function(title) {
return title.length;
},'Title cannot be blank');
*/
/**
* Statics
*/
BlockSchema.statics.load = function(id, cb) {
this.findOne({
_id: id
}).exec(cb);
};
BlockSchema.statics.fromHash = function(hash, cb) {
this.findOne({
hash: hash,
}).exec(cb);
};
module.exports = mongoose.model('Block', BlockSchema);

View File

@ -38,6 +38,7 @@
"mongoose": "~3.8.3",
"lodash": "~2.4.1",
"bower": "~1.2.8",
"bitcore": "*"
"bitcore": "*",
"buffertools": "*"
}
}

64
util/sync.js Executable file
View File

@ -0,0 +1,64 @@
#!/usr/bin/env node
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
require('buffertools').extend();
var RpcClient = require('../node_modules/bitcore/RpcClient').class();
var networks = require('../node_modules/bitcore/networks');
var Block = require('../app/models/Block');
var config = require('../config/config');
var mongoose = require('mongoose');
var networkName = process.argv[2] || 'testnet';
var genesisBlockHash = networks.testnet.genesisBlock.hash.reverse().toString('hex');
function syncBlocks(blockHash) {
rpc.getBlock(blockHash, function(err, blockInfo) {
if (err) {
console.log(err);
throw(err);
}
if ( ! ( blockInfo.result.height % 1000) )
console.log("Height:" + blockInfo.result.height);
Block.create( blockInfo.result, function(err, inBlock) {
if (err && err.toString().match(/E11000/)) {
// console.log("\twas there. Skipping");
return syncBlocks(blockInfo.result.nextblockhash);
}
if (err) throw(err);
if (inBlock.nextblockhash && ! inBlock.nextblockhash.match(/^0+$/) ) {
syncBlocks(inBlock.nextblockhash)
}
else {
mongoose.connection.close();
}
});
});
}
mongoose.connect(config.db);
var db = mongoose.connection;
var rpc = new RpcClient(config.bitcoind);
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
syncBlocks(genesisBlockHash);
});