Last active
July 25, 2022 08:12
-
-
Save viet-quocnguyen/46740aab8946f563e145ed6f64fb7394 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 :
But all that I get back is
[object Object]