Created
March 11, 2021 19:33
-
-
Save el-dockerr/f950ae44bb8389d1c99c3d69ee0e2e4e to your computer and use it in GitHub Desktop.
BlockChain Startup Code
This file contains 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 SHA256 = require("crypto-js/sha256"); | |
class CryptoBlock { | |
constructor(index, timestamp, data, precedingHash = " ") { | |
this.index = index; | |
this.timestamp = timestamp; | |
this.data = data; | |
this.precedingHash = precedingHash; | |
this.hash = this.computeHash(); | |
this.nonce = 0; | |
} | |
computeHash() { | |
return SHA256( | |
this.index + | |
this.precedingHash + | |
this.timestamp + | |
JSON.stringify(this.data) + | |
this.nonce | |
).toString(); | |
} | |
proofOfWork(difficulty) { | |
while ( | |
this.hash.substring(0, difficulty) !== Array(difficulty + 1).join("0") | |
) { | |
this.nonce++; | |
this.hash = this.computeHash(); | |
} | |
} | |
} | |
class CryptoBlockchain { | |
constructor() { | |
this.blockchain = [this.startGenesisBlock()]; | |
this.difficulty = 4; | |
} | |
startGenesisBlock() { | |
return new CryptoBlock(0, "01/01/2020", "Initial Block in the Chain", "0"); | |
} | |
obtainLatestBlock() { | |
return this.blockchain[this.blockchain.length - 1]; | |
} | |
addNewBlock(newBlock) { | |
newBlock.precedingHash = this.obtainLatestBlock().hash; | |
newBlock.hash = newBlock.computeHash(); | |
newBlock.proofOfWork(this.difficulty); | |
this.blockchain.push(newBlock); | |
} | |
checkChainValidity() { | |
for (let i = 1; i < this.blockchain.length; i++) { | |
const currentBlock = this.blockchain[i]; | |
const precedingBlock = this.blockchain[i - 1]; | |
if (currentBlock.hash !== currentBlock.computeHash()) { | |
return false; | |
} | |
if (currentBlock.precedingHash !== precedingBlock.hash) return false; | |
} | |
return true; | |
} | |
} | |
let myFraudCoinToScamYou = new CryptoBlockchain(); | |
console.log("Mining looooift....."); | |
myFraudCoinToScamYou.addNewBlock( | |
new CryptoBlock(1, "01/01/2021", { | |
sender: "Al capone", | |
recipient: "CDU", | |
qt : 400000 | |
})); | |
myFraudCoinToScamYou.addNewBlock( | |
new CryptoBlock(2, "01/02/2021", { | |
sender: "NRA", | |
recipient: "Trump", | |
qt : 300000 | |
})); | |
console.log(myFraudCoinToScamYou.checkChainValidity()); | |
console.log(JSON.stringify(myFraudCoinToScamYou, null, 4)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment