lab 15
by HSilvaDaytona
HTML
Assignment 15
<p />
Enter Value<br />
<input type="text" id="BitVal" value="9">
<button id="bitValButt">Blockchain</button>
<button id="ManButt">Manipulate</button>
<p id="wherePrint">
<p id="demo">
JavaScript
document.getElementById("bitValButt").addEventListener("click", function () {
addData();
});
document.getElementById("ManButt").addEventListener("click", function () {
ManData();
});
function hashcode (str) {
var i = str.length
var hash1 = 5381
var hash2 = 52711
while (i--) {
const char = str.charCodeAt(i)
hash1 = (hash1 * 33) ^ char
hash2 = (hash2 * 33) ^ char
}
return (hash1 >>> 0) * 4096 + (hash2 >>> 0)
}
class Block {
constructor( data, previousHash = '') {
this.previousHash = previousHash;
this.data = data;
this.hash = this.calculateHash();
}
calculateHash() {
return hashcode( this.previousHash + JSON.stringify(this.data)).toString();
}
}
class Blockchain{
constructor() {
this.chain = [this.createGenesisBlock()];
}
createGenesisBlock() {
return new Block( "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 SilvaCoin = new Blockchain();
SilvaCoin.addBlock(new Block({ amount: 4}));
SilvaCoin.addBlock(new Block({ amount: 8 }));
//Is the Blockchain Valid
console.log('Blockchain valid? ' + SilvaCoin.isChainValid());
...