A15 Block Chain LL

Block Chain Double linked list

by scotp71

HTML

<h1>
Block Chain
</h1>
<br/>

<input type="textbox" id="v" value="Enter Data" />
<input type="button" value="Add Block" onclick="addNode()"/>



<input type="button" value="Change Head" onclick="changeHead()"/>

<div id="output">
</div>

JavaScript

function BlockChain(){

	this.head = null;
  this.tail = null;
  this.length = 0;
	var chain = this.createGenBlock();
	
  this.chain = chain;
}

function Node(_content, _prevHash){
	this.next = null;
  this.prev = null;
  this.content = _content;
  this.hash = null;
	this.prevHash = _prevHash;
}

calculateHash = function(_content, prevHash){
	var M = 128;
	var ch = (_content + prevHash);
  var len = ch.length;
  var num = 0;
  var sum = 0;
  for (var i=0; i<len; i++){
  	num = ch.charCodeAt(i);
    sum += num;
  }
	var key = sum % M;
  
	return key;
}
	
  

BlockChain.prototype.createGenBlock = function(){
	var node = new Node("Genesis Block", "0");
  this.head = node;
  this.tail = node;
  this.head.hash = calculateHash("Genesis Block", "0");
  this.length = 1;
  return this;
  }
  
BlockChain.prototype.getLatestBlock = function(){
	var lastBlock = this.chain.tail;
  return lastBlock;
}

BlockChain.prototype.add = function(_content) {
	var newBlock = new Node(_content);  
  newBlock.prevHash = this.getLatestBlock().hash;
  newBlock.hash = calculateHash(_content, newBlock.prevHash)
  
  if (this.head == null) {
  	this.head = newBlock; this.length = 1;
    return node;
  }
  
  if (this.tail == null) {
  	this.tail = newBlock;
    this.tail.prev = this.head;
    this.head.next = this.tail;
    this.length = 2;
    return newBlock;
  }
	
	this.tail.next = newBlock; 
  newBlock.prev = this.tail;
  this.tail = newBlock;
  this.length++;
  return newBlock;
}

BlockChain.prototype.addNewHead = function(_newHead){
	var y = this.head.next;
  var z = this.head.prev;
  this.head.next.prev = _newHead;
  this.head = _newHead;
  this.head.next = y;
  this.head.prev = z;
}

BlockChain.prototype.isChainValid = function() {
	if (this.head == null) return "Empty List"
  var s = "Chain is not valid";
  var node = this.tail.prev;
  
  while (node.prev != null) {
		var prevNode = node.prev;
    var prevHash = node.prevHash;
    if(prevNode.hash!=prevHash){
    	return s;
    }
 ...