Skip to content

Instantly share code, notes, and snippets.

@cardeol
Last active March 31, 2018 11:05
Show Gist options
  • Save cardeol/75cdcad3f59da66d2d868b4876111e53 to your computer and use it in GitHub Desktop.
Save cardeol/75cdcad3f59da66d2d868b4876111e53 to your computer and use it in GitHub Desktop.
function BlockChain(difficulty) {
this.blocks = [];
this.difficulty = difficulty;
this.add = function(block) { // a new kid on the blockchain
this.blocks.push(block);
}
this.get = function(i) { // get the block # i
return this.blocks[i];
}
this.getDifficulty = function() { // the the current difficulty level
return this.difficulty;
}
this.size = function() { // How many blocks ?
return this.blocks.length;
}
this.getLast = function() { // give me the latest
return this.blocks.length > 0 ? this.blocks[this.blocks.length - 1] : null;
}
this.isValid = function(currentBlock, previousBlock, diffTarget) { // A helper to validate the current Block with the previous in the blockchain
currentHash = currentBlock.getHash();
if( (currentHash.indexOf(diffTarget) < 0) // the block has not been mined
|| (currentHash != currentBlock.computeHash()) // the block hash has been altered
|| (currentBlock.getPreviousHash() != previousBlock.getHash())) { // the previous Block hash has changed
return false;
}
return true;
}
this.checkDataIntegrity = function() { // Are you trying to cheat ?
var curBlock,prevBlock,currentTarget;
var difficultyTarget = Array(this.difficulty).join("0");
for(var i = 1; i < this.blocks.length; i++) {
curBlock = this.blocks[i];
prevBlock = this.blocks[i-1];
if(!this.isValid(curBlock , prevBlock, difficultyTarget)) {
console.log("There is an incosistency in the blockchain, block # " + i);
return false;
}
}
console.log("The Blockchain is valid!");
return true;
}
}
module.exports = BlockChain;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment