JSFiddle - React, Tailwind, and code Playground
by zazagalaxy
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-sha256/0.9.0/sha256.min.js"></script>
<h3><center>
Assignment 15: Blockchain
</center>
</h3>
<br>
Enter a value to add a new block to blockchain.
<input type="textbox" id="addval" />
<input type="button" id="addblock" value="Add Block" onclick="addblock();" />
<br>
<br>
<input type="button" id="check" value="Check if Valid" onclick="check();" />
<input type="button" id="inval" value="Invalidate" onclick="butcoin.invalidate();" />
<input type="button" id="inval" value="Print blockchain" onclick="butcoin.print();" />
<br>
<br>
<div id = "output">
</div>
JavaScript
//collaboration with Eugene
// Function to get 64-bit hash code.
var gethash = function(value) {
return CryptoJS.SHA256(value + randomstr());
}
// Create block to be inserted into Blockchain
var Block = function(value, prev) {
this.next = null;
this.prev = null;
this.data = value;
this.hash = gethash(this.data);
this.prevhash = prev;
}
// Create blockchain
var Blockchain = function() {
this.length = 0;
this.head = null;
this.tail = null;
this.genesis = this.push("Genesis", 0);
}
// Method to push new blocks into blockchain
Blockchain.prototype.push = function(value, prev){
let block = new Block(value, prev);
if (!this.head) {
this.head = block;
this.length = 1;
this.prevhash = this.getprev(block);
return block;
}
if (!this.tail) {
this.tail = block;
this.tail.prev = this.head;
this.head.next = this.tail;
this.length = 2;
this.prevhash = this.getprev(block);
return block;
}
this.tail.next = block;
block.prev = this.tail;
this.tail = block;
this.length += 1;
this.hash = gethash(value);
this.prevhash = this.getprev(block);
console.log(this.prevhash);
return block;
}
// Method to get previous blocks hash and set it to
// the prevhash property of the current block.
Blockchain.prototype.getprev = function(block) {
var current = this.head;
for (var i = 0; i < this.length; i++) {
if (current.next) {
if (block.hash == current.next.hash) {
block.prevhash = current.hash;
return block.prevhash;
} else {
current = current.next;
}
}
}
}
// Method to print the blockchain (was used for testing)
Blockchain.prototype.print = function() {
let current = this.head;
var out = "";
if (butcoin.isvalid()) {
for (var i = 0; i < this.length; i++) {
out += "Block " + (i + 1) + " Hash: " + current.hash + "<br>";
current = current.next;
}
}...