Skip to content

Instantly share code, notes, and snippets.

@viet-quocnguyen
Last active July 25, 2022 08:12
Show Gist options
  • Save viet-quocnguyen/46740aab8946f563e145ed6f64fb7394 to your computer and use it in GitHub Desktop.
Save viet-quocnguyen/46740aab8946f563e145ed6f64fb7394 to your computer and use it in GitHub Desktop.
const hash = require("crypto-js/sha256");
class Block {
constructor(previousHash, data) {
this.data = data;
this.hash = this.calculateHash();
this.previousHash = previousHash;
this.timeStamp = new Date();
this.proofOfWork = 0;
}
calculateHash() {
return hash(
this.previousHash +
JSON.stringify(this.data) +
this.timeStamp +
this.proofOfWork
).toString();
}
mine(difficulty) {
while (!this.hash.startsWith("0".repeat(difficulty))) {
this.proofOfWork++;
this.hash = this.calculateHash();
}
}
}
class Blockchain {
constructor() {
let genesisBlock = new Block("0", { isGenesis: true });
this.chain = [genesisBlock];
}
addBlock(data) {
let lastBlock = this.chain[this.chain.length - 1];
let newBlock = new Block(lastBlock.hash, data);
newBlock.mine(2); // find a hash for new block
this.chain.push(newBlock);
}
isValid() {
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;
}
}
@webzest
Copy link

webzest commented Dec 10, 2021

I tried to run this piece of code locally in Visual Studio Code / Ubuntu20.04. It returns null. Would you help me to get the blockchain output?
I also tried :

let blockchain = new Blockchain();

blockchain.addBlock({
  from: "Viet",
  to: "David",
  amount: 100,
});

blockchain.addBlock({
  from: "Adam", 
  to: "Beck",
  amount: 150,
});

console.log (String(blockchain.chain[1].data));

But all that I get back is [object Object]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment