<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/json2/20160511/json2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-sha256/0.9.0/sha256.min.js"></script>
<div id = "output">
</div>
<br>
Enter a value to add a new block.
<input type="textbox" id="addval" />
<input type="button" id="addblock" value="Add Block" onclick="addblock();" />
<br>
<br>
Enter a value to check for in the blockchain.
<input type="textbox" id="checkval" />
<input type="button" id="check" value="Check if Valid" onclick="check();" />
JavaScript
var gethash = function(value) {
return sha256(value);
}
var Block = function(value, prev) {
this.next = null;
this.prev = null;
this.data = value.toString();
this.hash = gethash(this.data);
this.prevhash = prev;
}
var Blockchain = function() {
this.length = 0;
this.head = null;
this.tail = null;
this.genesis = this.push("Genesis", 0);
}
Blockchain.prototype.push = function(value, prev){
let block = new Block(value, prev);
if (this.head === null) {
this.head = block;
this.length = 1;
return block;
}
if (this.tail === null) {
this.tail = block;
this.tail.prev = this.head;
this.head.next = this.tail;
this.length = 2;
return block;
}
this.tail.next = block;
block.prev = this.tail;
this.tail = block;
this.length += 1;
return block;
}
Blockchain.prototype.print = function() {
let current = this.head;
var out = "";
for (var i = 0; i < this.length; i++) {
current = current.next;
}
}
Blockchain.prototype.isvalid = function(value) {
var current = this.head;
var hash = sha256(value);
for (var i = 0; i < this.length; i++) {
if (current.hash == hash) {
return true;
} else {
if (current.next != null) {
current = current.next;
} else {
return false;
}
}
}
}
var addblock = function() {
var value = document.getElementById("addval").value.toString();
pesos.push(value);
var out = "Block added: " + sha256(value);
document.getElementById("output").innerHTML = out;
}
var check = function() {
var value = document.getElementById("checkval").value.toString();
var hash = sha256(value);
var out = pesos.isvalid(hash);
document.getElementById("output").innerHTML = "Is valid: " + out;
}
let pesos = new...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.