JSFiddle - React, Tailwind, and code Playground

by leiperte

HTML

<input type=textbox id="content" />
<input type="button" value="Push to Node" onclick="createList()" />
<p id="output"></p>

JavaScript

//Assignment 15

const SHA256 = require('crypto-js/sha256');

class Block{
	constructor(index, timestamp, data, previousHash = ''){
  	this.index = index;
    this.timestamp = timestamp;
    this.data = data;
    this.previousHash = previousHash;
    this.hash = this.calculateHash();
  }
  
  calculateHash(){
  	return SHA256(this.index + this.previousHash + this.timestamp + JSON.stingify(this.data)).toString();
  }
}

class Blockchain{
	constructor(){
  	this.chain = [this.createGenesisBlock()];
  }
  
  createGenesisBlock(){
  	return new Block(0, "01/01/2017", "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.hash !== previousBlock.hash) {
        return false;
      }
    }

    return true;
  }
}

Blockchain.prototype.push = function(content) {
  var node = new Block();
  node.content = content;

  if (this.head === null) {
    this.head = node;
    this.length = 1;
    return node;
  }

  if (this.tail === null) {
    this.tail = node;
    this.tail.previous = this.head;
    this.head.next = this.tail;
    this.length = 2;
    return node;
  }

  this.tail.next = node;
  node.previous = this.tail;
  this.tail = node;
  this.length++;
  return node;

}
Blockchain.prototype.print = function() {
  if (this.head == null) {return "Empty List";}
  var s = "";
  var node = this.head;
  while (node != null) {
    s += node.content + "   ";
    node = node.next;
  }
  return s;
}
var bList = new Blockchain();

function createList() {
	var n = document.getElementById("content").value;
   ...