Created
March 30, 2018 22:31
-
-
Save cardeol/0c4c5f36c90a260bcb29ecd3d9ebe8c2 to your computer and use it in GitHub Desktop.
A Javascript Block class for a blockchain
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var sha256 = require("sha256"); | |
var method = Block.prototype; | |
function Block(data, previousHash) { | |
if(typeof previousHash === "undefined") previousHash = "genesis_block"; | |
this._previousHash = previousHash; | |
this._data = JSON.stringify({ data: data }); | |
this._nonce = 0; | |
this._timeStamp = new Date().getTime(); | |
this._hash = this.computeHash(); // constructor | |
} | |
method.mineBlock = function(difficulty) { | |
var targetDifficulty = Array(difficulty).join("0"); | |
// the objective is creating a hash containing a string of '0's based on the difficulty | |
while(this._hash.indexOf(targetDifficulty) < 0) { | |
this._nonce++; // the nounce must change in order to get a different sha1 hash | |
this._hash = this.computeHash(); | |
} | |
// the new hash must be something like this (containing N zeroes) | |
// 0000000a2d032b6d98651082082b47ace27621cbaf2aac654e58ad0dfbb2c697 | |
console.log("BLOCK MINED ==> " + this._hash); | |
} | |
method.getData = function() { | |
var e = JSON.parse(this._data); | |
return e.data; | |
} | |
method.getHash = function() { | |
return this._hash; | |
} | |
method.getPreviousHash = function() { | |
return this._previousHash; | |
} | |
method.computeHash = function() { | |
return sha256( | |
this.previousHash | |
+ this._data | |
+ this._timeStamp | |
+ this._nonce | |
); | |
}; | |
module.exports = Block; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment