Skip to content

Instantly share code, notes, and snippets.

@andrewbruner
Created August 15, 2021 15:30
Show Gist options
  • Select an option

  • Save andrewbruner/af95c28b93aac6b5d961a883e263e9f3 to your computer and use it in GitHub Desktop.

Select an option

Save andrewbruner/af95c28b93aac6b5d961a883e263e9f3 to your computer and use it in GitHub Desktop.
Simple JavaScript Blockchain
// Block Object
function Block(previousHash, data) {
this.previousHash = previousHash;
this.data = data;
this.hash = SHA256(JSON.stringify(this));
}
// Blockchain Object
function Blockchain() {
// Chain of all blocks
let chain = [];
// Add block to chain
this.add = function(data) {
let previousHash = chain[chain.length - 1].hash;
let block = new Block(previousHash, data);
chain.push(block);
}
// Print chain to console
this.print = function() {
console.log(JSON.stringify(chain, null, 2));
}
// Add Genesis Block
chain.push(new Block('0', 'Genesis Block'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment