Building a Blockchain with UI in Javascript

Last updated

Antonio Ufano avatar

Antonio Ufano

Last week I decided I wanted to build a simple application to create and display what a Blockchain is and how its blocks are all linked to one another. First I created a couple of classes in Javascript to define the Blockchain itself and each of the blocks and then, I added the methods to initialise the chain, add new blocks and validate its contents. I had to import the crypto-js package to generate the hash of each block. Once the basic functionality was done and I was able to test it in the terminal with Node, I built a basic interface using Vue.js, creating one component for each JavaScript class. To compile all components into a single .js file I used Webpack 4. You can download all the code from the following repo. Find below some more details of how I did it.

The Blockchain and Block classes

The Block class is very simple. It just has a constructor that receives the data the block is going to store. For simplicity I store just a string but we could store a JSON or whatever we want. It also has a calculateHash method, which returns the hash produced by the SHA256 crypto module (which is imported in the first line). The Blockchain class contains just a chain attribute, which is initialised to an array with one Block in the constructor. This first block is called the genesis block and as it cannot contain the hash of the previous one (because there isn't...) the value is hardcoded to zero. For each new block added to the chain we'll have to add to it the previous block's hash and then calculate its own as seen below:

addBlock(newBlock){
    //assign index
    newBlock.index = this.chain.length;
    //assign hashes
    newBlock.previousHash = this.getLatestBlock().hash;
    newBlock.hash = newBlock.calculateHash();
    //add to the chain
    this.chain.push(newBlock);
}

Creating the UI with Vue components

Following the same approach as with the back end, I created two components for the UI: a chain component and a block component. As the chain component will be the one handling most of the logic calling the methods from the Javascript classes, I imported them in the script section:\r\n

//import other components
import block from './block.vue'

//import JS classes
import Blockchain from '../Blockchain'
import Block from '../Block'

Then I defined the methods in the component that will call the different methods from the class to initialize the chain, add blocks and validate:

methods:{
    initChain(){
        console.log('initializing chain...');
        this.blockchain = new Blockchain;
        this.initialized = true;
        this.message = 'Yay! I have ' + this.blockchain.chain.length + ' Blocks!';
    },
    addBlock(){
        this.blockchain.addBlock(new Block('', this.new_block.data ));
        this.new_block.data = '';
        this.message = 'Yay! I have ' + this.blockchain.chain.length + ' Blocks!';

    },
    validateChain(){
        console.log('Analysing blockchain...');
        this.invalid_block = this.blockchain.isValid();
    }
}

Regarding the templates, the chain component has a small form to enter the data we want to add to the next block and it also renders as many block components as we have in the chain using Vue's v-for directive. The block component receives the values of the block as props and prints them in inputs as I want the user to be able to modify the content of the blocks to invalidate the blockchain.

Finally I included some basic styling using Bootstrap 4. When the chain is valid, it's green and when the user modifies any of the block's data and validates it, the validateChain method returns the index of the invalid block, which is highlighted in red.

Screenshot of the blockchain UI

Conclusion

This is a very simple example to explain the basic principles of a Blockchain. I wanted to code it basically to practise a little bit with Javascript, Node packages and Webpack, which is used to compile all Javascript into a single js file. You can clone it from the repository and run it locally following the documentation. I hope it helps you understand better the properties of a Blockchain or how to build applications with Node and Vue.js.

Happy coding!

If you enjoyed this article consider sharing it on social media or buying me a coffee ✌️

Oh! and don't forget to follow me on Twitter where I share tons of dev tips 🤙

Other articles that might help you

my projects

Apart from writing articles in this blog, I spent most of my time working on my personal projects.

lifeboard.app logo

theLIFEBOARD.app

theLIFEBOARD is a weekly planner that helps people achieve their goals, create new habits and avoid burnout. It encourages you to plan and review each week so you can easily identify ways to improve your productivity while keeping track of your progress.

Request early access
quicktalks.io logo

Quicktalks.io

Quicktalks is a place where indie hackers, makers, creators and entrepreneurs share their knowledge, ideas, lessons learned, failures and tactics they use to build successfull online products and businesses. It'll contain recorded short interviews with indie makers.

Message me to be part of it