Skip to content

Instantly share code, notes, and snippets.

@mitramejia
Last active January 19, 2018 20:19
Show Gist options
  • Save mitramejia/2abfa7c0716eb3a1230602f87ee26a99 to your computer and use it in GitHub Desktop.
Save mitramejia/2abfa7c0716eb3a1230602f87ee26a99 to your computer and use it in GitHub Desktop.
Simple Blockchain made with JS
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();
this.nonce = 0;
}
calculateHash(){
return SHA256(
this.index +
this.prevoiusHash +
this.timestamp +
this.nonce +
JSON.stringify(this.data)
).toString();
}
// We need to make the stat of the hash begin with a certian amount of zeroes
mineBlock(difficulty) {
while(this.hash.substring(0, difficulty) !== Array(difficulty+1).join("0")){
this.nonce++;
this.hash = this.calculateHash();
}
console.log("Block mined:" + this.hash)
}
}
class Blockchain {
constructor(){
this.difficulty = 3;
this.chain = [this.createGenesisBlock()];
}
createGenesisBlock(){
return new Block(0, '01/01/2017', 'Genesis block', '0');
}
getLatestBlock(){
return this.chain[this.chain.length - 1];
}
addBlock(newBlock){
newBlock.previousHash = this.getLatestBlock().hash;
newBlock.mineBlock(this.difficulty)
newBlock.hash = newBlock.calculateHash();
this.chain.push(newBlock);
}
}
let mitraCoin = new Blockchain();
mitraCoin.createGenesisBlock()
mitraCoin.addBlock(new Block(1, '10/07/2017', { amount: 5}))
mitraCoin.addBlock(new Block(2, '10/07/2017', { amount: 3}))
console.log(JSON.stringify(mitraCoin, null, 4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment