Articles → Blockchain → Adding A Block In Blockchain Using Javascript
Adding A Block In Blockchain Using Javascript
Adding A Mineblock Function
mineBlock(difficulty) {
while (this.hash.toString().substring(0, difficulty) !== Array(difficulty + 1).join("0")) {
this.nonce++;
this.hash = this.calculateHash();
}
console.log("Block Successfully hashed: " + this.hash);
console.log("Nonce: " + this.nonce);
}
- Comparing the block hash with target hash.
- If hash is not matched then calculate the hash again by adding the nonce.
- Compare again till the time hash is not matched.
Output
Click to Enlarge
Full Code
const SHA256 = require('crypto-js/sha256');
class Block {
constructor(index, timestamp, data, previousHash) {
this.index = index;
this.timestamp = timestamp;
this.data = data;
this.previousHash = previousHash;
this.nonce = 0;
this.hash = this.calculateHash();
}
calculateHash() {
return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data) + this.nonce);
}
mineBlock(difficulty) {
while (this.hash.toString().substring(0, difficulty) !== Array(difficulty + 1).join("0")) {
this.nonce++;
this.hash = this.calculateHash();
}
console.log("Block Successfully hashed: " + this.hash);
console.log("Nonce: " + this.nonce);
}
}
class Blockchain {
constructor() {
this.chain = [this.createGenesisBlock()];
this.difficulty = 3;
}
createGenesisBlock() {
return new Block(0, '02/05/2020', 'Genesis Block', "0");
}
getlatestBlock() {
return this.chain[this.chain.length - 1];
}
addBlock(newBlock) {
newBlock.previousHash = this.getlatestBlock().previousHash;
//newBlock.hash = newBlock.calculateHash();
newBlock.mineBlock(this.difficulty);
this.chain.push(newBlock);
}
}
let demoChain = new Blockchain();
console.log("Starting................");
demoChain.addBlock(
new Block(1, '02/05/2020', {
amount: 10
}));
console.log("Secondly................");
demoChain.addBlock(
new Block(2, '02/05/2020', {
amount: 25
}));