2014-01-06 18:50:29 -08:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Module dependencies.
|
|
|
|
*/
|
2014-01-07 11:49:42 -08:00
|
|
|
var mongoose = require('mongoose'),
|
|
|
|
Schema = mongoose.Schema;
|
2014-01-06 18:50:29 -08:00
|
|
|
|
2014-01-07 11:49:42 -08:00
|
|
|
var async = require('async');
|
|
|
|
var Transaction = require('./Transaction');
|
2014-01-06 18:50:29 -08:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Block Schema
|
|
|
|
*/
|
|
|
|
var BlockSchema = new Schema({
|
2014-01-07 04:48:31 -08:00
|
|
|
hash: {
|
|
|
|
type: String,
|
2014-01-06 18:50:29 -08:00
|
|
|
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: {
|
2014-01-07 04:48:31 -08:00
|
|
|
type: String,
|
2014-01-06 18:50:29 -08:00
|
|
|
index: true,
|
|
|
|
unique: true,
|
|
|
|
},
|
|
|
|
nextblockhash: {
|
2014-01-07 04:48:31 -08:00
|
|
|
type: String,
|
2014-01-06 18:50:29 -08:00
|
|
|
index: true,
|
|
|
|
unique: true,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
2014-01-07 11:49:42 -08:00
|
|
|
BlockSchema.methods.explodeTransactions = function(next) {
|
|
|
|
|
|
|
|
// console.log('exploding %s', this.hash, typeof this.tx);
|
|
|
|
|
|
|
|
async.forEach( this.tx,
|
|
|
|
function(tx, callback) {
|
|
|
|
// console.log('procesing TX %s', tx);
|
|
|
|
Transaction.create({ hash: tx }, function(err) {
|
|
|
|
if (err && ! err.toString().match(/E11000/)) {
|
|
|
|
return callback();
|
|
|
|
}
|
|
|
|
if (err) {
|
|
|
|
|
|
|
|
return callback(err);
|
|
|
|
}
|
|
|
|
return callback();
|
|
|
|
|
|
|
|
});
|
|
|
|
},
|
|
|
|
function(err) {
|
|
|
|
if (err) return next(err);
|
|
|
|
return next();
|
|
|
|
}
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
2014-01-06 18:50:29 -08:00
|
|
|
/**
|
|
|
|
* Validations
|
|
|
|
*/
|
|
|
|
|
|
|
|
/*
|
|
|
|
BlockSchema.path('title').validate(function(title) {
|
|
|
|
return title.length;
|
|
|
|
},'Title cannot be blank');
|
|
|
|
*/
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Statics
|
|
|
|
*/
|
|
|
|
|
|
|
|
BlockSchema.statics.load = function(id, cb) {
|
2014-01-07 04:48:31 -08:00
|
|
|
this.findOne({
|
|
|
|
_id: id
|
|
|
|
}).exec(cb);
|
2014-01-06 18:50:29 -08:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
BlockSchema.statics.fromHash = function(hash, cb) {
|
2014-01-07 04:48:31 -08:00
|
|
|
this.findOne({
|
|
|
|
hash: hash,
|
|
|
|
}).exec(cb);
|
2014-01-06 18:50:29 -08:00
|
|
|
};
|
|
|
|
|
2014-01-07 11:49:42 -08:00
|
|
|
|
2014-01-06 18:50:29 -08:00
|
|
|
module.exports = mongoose.model('Block', BlockSchema);
|