main.js
const SHA256 = require('crypto-js/sha256');
class Block {
constructor(index, timestamp, data, prevHash = '') {
this.index = index;
this.timestamp = timestamp;
this.data = data;
this.prevHash = prevHash;
this.hash = this.calculateHash();
}
calculateHash() {
return SHA256(this.index + this.prevHash + this.timestamp + JSON.stringify(this.data)).toString();
}
}
class Blockchain {
constructor() {
this.chain = [this.createGenesisBlock()];
}
createGenesisBlock() {
return new Block(0, "01/01/2021", "Genesis block", "0");
}
getLatestBlock() {
return this.chain[this.chain.length - 1];
}
addBlock(newBlock) {
newBlock.prevHash = this.getLatestBlock().hash;
newBlock.hash = newBlock.calculateHash();
this.chain.push(newBlock);
}
isChainValid() {
for(let i=1; i < this.chain.length; i++) {
const currentBlock = this.chain[i];
const prevBlock = this.chain[i-1];
if(currentBlock.hash !== currentBlock.calculateHash()) {
return false;
}
if(currentBlock.prevHash != prevBlock.hash) {
return false;
}
}
return true;
}
}
let tcoin = new Blockchain();
tcoin.addBlock(new Block(1, "03/09/2021", {amt: 100}));
tcoin.addBlock(new Block(1, "04/09/2021", {amt: 200}));
console.log(tcoin.isChainValid());
console.log(JSON.stringify(tcoin, null, 4));
//tempering data
tcoin.chain[2].amt = 2000;
console.log(JSON.stringify(tcoin, null, 4));
console.log(tcoin.isChainValid());
Proof of Work
const SHA256 = require('crypto-js/sha256');
class Block {
constructor(index, timestamp, data, prevHash = '') {
this.index = index;
this.timestamp = timestamp;
this.data = data;
this.prevHash = prevHash;
this.hash = this.calculateHash();
this.nonce = 0;
}
calculateHash() {
return SHA256(this.index + this.prevHash + this.timestamp + JSON.stringify(this.data) + this.nonce).toString();
}
mineBlock(complexity) {
while(this.hash.substring(0, complexity) !== Array(complexity + 1).join("0")) {
this.nonce++;
//console.log(this.nonce);
this.hash = this.calculateHash();
}
console.log(`Block mined: ${this.hash}`);
}
}
class Blockchain {
constructor(complexity = 0) {
this.chain = [this.createGenesisBlock()];
this.complexity = complexity;
}
createGenesisBlock() {
return new Block(0, "01/01/2021", "Genesis block", "0");
}
getLatestBlock() {
return this.chain[this.chain.length - 1];
}
addBlock(newBlock) {
newBlock.prevHash = this.getLatestBlock().hash;
//newBlock.hash = newBlock.calculateHash();
newBlock.mineBlock(this.complexity);
this.chain.push(newBlock);
}
isChainValid() {
for(let i=1; i < this.chain.length; i++) {
const currentBlock = this.chain[i];
const prevBlock = this.chain[i-1];
if(currentBlock.hash !== currentBlock.calculateHash()) {
return false;
}
if(currentBlock.prevHash != prevBlock.hash) {
return false;
}
}
return true;
}
}
let tcoin = new Blockchain(5);
console.log("Mining Block 1...");
tcoin.addBlock(new Block(1, "03/09/2021", {amt: 100}));
console.log("Mining Block 2...");
tcoin.addBlock(new Block(1, "04/09/2021", {amt: 200}));
console.log(JSON.stringify(tcoin, null, 4));