xxxxxxxxxx
67
// define a block
// ##############
class Block {
constructor(index, previousHash, data) {
this.index = index;
this.previousHash = previousHash;
this.timestamp = new Date().getTime() / 1000;
this.data = data;
this.hash = calculateHash(index, previousHash, this.timestamp, data);
}
}
// generate genisis block
// ######################
let poem = "Ode to a Chain of Blocks";
let fall = new Block(0, 0, poem);
let blocks = [fall];
// generate new block
// ##################
function generateNextBlock(blockData) {
const previousBlock = blocks[blocks.length - 1];
const nextIndex = previousBlock.index + 1;
const newBlock = new Block(nextIndex,previousBlock.hash,blockData);
blocks.push(newBlock);
}
// calculate hash
// ##############
function calculateHash(index, previousHash, timestamp, data) {
const str =
index.toString() +
previousHash.toString() +
timestamp.toString() +
data.toString;
var h = 0,
l = str.length,
i = 0;
if (l > 0) while (i < l) h = ((h << 5) - h + str.charCodeAt(i++)) | 0;
return h;
}
function setup() {
createCanvas(400, 400);
background(255);
frameRate(1);
}
function draw() {
if(frameCount < 3){
this.generateNextBlock(random()+"");
rectMode(CENTER);noStroke();fill(random(0,255),100);
rect(random(0,width),random(0,width),5,5);
console.log(blocks[frameCount-1]);
}
}