Assignment 15
by MimiE
HTML
<br><br>
Input a Number:
<input id="text"><br><br>
<button onclick="add()" id="output0">Add Blockchain</button>
<button onclick="invalidate()" id="output1">Invalidate Blockchain</button><br><br>
<div id="value"><hr></div>
<br>
JavaScript
// linked list
var Node = function(a) {
this.next = null;
this.prev = null;
this.key = a;
return this;
}
var List = function(a) {
this.head = null;
this.tail = null;
this.length = 0;
return this;
}
// converts list to string
List.prototype.listToString = function() {
var str = ''; //insert string here
var anode = this.head;
while (anode != null) {
str += anode.key + '<br>';
anode = anode.next;
}
return str;
}
List.prototype.push = function(a) {
var node = new Node(a);
// node.c = a;
if (this.head == null) {
this.head = node;
this.tail = node;
this.length++;
return node;
}
node.prev = this.tail;
this.tail.next = node;
this.tail = node;
this.length++;
return node;
}
List.prototype.pop = function() {
var poppedNode = this.tail;
if (this.head == null) {
alert(''); //alerts.
return null;
}
if (this.head == this.tail) {
this.head = null;
this.tail = null;
this.length--;
return poppedNode;
}
this.tail = this.tail.prev;
this.tail.next = null;
this.length--;
return poppedNode;
}
List.prototype.peek = function(){
return this.tail;
}
class Block {
constructor(data, previousHash = ''){
this.data = data;
this.previousHash = previousHash;
this.hash = '';
}
calculateHash(){
return SHA1(this.previousHash + JSON.stringify(this.data)).toString();
}
}
class Blockchain {
constructor() {
this.chain = new List();
this.createGenesisBlock();
}
createGenesisBlock(){
const block = new Block("Genesis Block", "0");
block.hash = block.calculateHash();
this.chain.push(block);
}
getLatestBlock() {
return this.chain.peek();
}
addBlock(amt) {
const block = new Block(amt);
block.previousHash = this.getLatestBlock().key.hash;
block.hash = block.calculateHash();
this.chain.push(block);
var outputArea = document.getElementById('value');
outputArea.innerHTML +=...