simpleblockchainjs
Version:
A simple example of a working model of blockchain.
61 lines (49 loc) • 1.8 kB
JavaScript
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.hash = this.calculateHash();
}
calculateHash() {
return SHA256(this.index + this.timestamp + this.previousHash + JSON.stringify(this.data)).toString();
}
}
class BlockChain {
constructor() {
this.chain = [this.createGenesisBlock()];
}
createGenesisBlock() {
return new Block(0, new Date().toISOString(), "Genesis Block", "0");
}
getLatestBlock() {
return this.chain[this.chain.length - 1];
}
addBlock(newBlock) {
newBlock.previousHash = 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 previousBlock = this.chain[i - 1];
if(currentBlock.hash !== currentBlock.calculateHash()) {
return false;
}
if(currentBlock.previousHash !== previousBlock.hash) {
return false;
}
}
return true;
}
}
let vickylanceCoin = new BlockChain();
vickylanceCoin.addBlock(new Block(vickylanceCoin.chain.length, new Date().toISOString(), { amount: 4 }));
vickylanceCoin.addBlock(new Block(vickylanceCoin.chain.length, new Date().toISOString(), { amount: 10 }));
// console.log(new Date().toISOString());
console.log('====================================');
console.log(JSON.stringify(vickylanceCoin, null, 4));
console.log('====================================');