Created
August 15, 2021 15:30
-
-
Save andrewbruner/af95c28b93aac6b5d961a883e263e9f3 to your computer and use it in GitHub Desktop.
Simple JavaScript Blockchain
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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