A blockchain in your browser

Nima Boustanian
7 min readMay 7, 2018

--

This article teaches the fundamentals of blockchain technology by showing you how to build your own blockchain. We will walk through core concepts for people who are both non-technical and technical, and the final product can be run in any web browser. The blockchain is a very simplified version of how the Bitcoin network is setup, so after this tutorial you’ll actually be the blockchain person at the next cocktail party.

Prerequisites:

  • A basic understanding of programming
  • A web browser
  • 30 minutes of your time

Step 1 - Blockchain architecture

Below is a simple illustration of how a blockchain transaction works. Understanding a transaction covers a lot of ground and makes understanding blockchain technology in general much easier.

A blockchain transaction

So here’s a breakdown of what’s going on in the illustration:

  • Network: the network consists of computers (miners) which each hold a copy of the blockchain.
  • Address: for simplicity’s sake, we can think of an address as a digital wallet which holds your coins. In reality it’s a bit more complicated than that (https://en.bitcoin.it/wiki/Address).
  • Transaction: a transaction takes place when coins are sent to and from addresses in the network.
  • Block: a block is a list of transactions. Each block in the Bitcoin network for instance contains at least 1000 transactions and some other information about the block itself. We’ll go through the block details later in the code.
  • Miner: a miner is a computer whose job it is to pick up transactions and put them into new blocks. Whenever a miner manages to mine a block it receives transaction fees and a number of coins as reward, hence the expression ‘mining coins’. In the Bitcoin network for instance, a new block is added about every 10th minute. Any computer can be turned into a miner, even the one you’re using to read this article on!
  • Blockchain: the blockchain is simply a database of all the mined blocks. When a miner manages to mine a new block, it message other miners in the network about it. The other miners then accept the new block and they all add it to their copy of the blockchain.

Step 2 - Creating the test code

We will create our blockchain in JavaScript, and all of the code can be run directly in your browser. Before we start I’d like to give a huge shout out to https://medium.com/@lhartikk and https://www.savjee.be/ as I’ve heavily relied on their work for this tutorial.

If you read Step 1 — Blockchain architecture then the above code should be pretty straightforward.

  • Lines 1 and 2 create new addresses to send/receive coins from. The first parameter is the address name, and can be set to anything you’d like. The second parameter is the balance (number of coins) the address should initially contain.
  • Then we create new transactions on lines 4–7. Each transaction contains a from address, a to address, and the amount of coins that should be sent.
  • Then we create the network, which basically is a list of miners. Also remember that each miner needs a copy of the blockchain, so we give them each a new Blockchain copy, with a empty block to go with it. This block is generally called the genesis block.
  • After we have the network setup we just call the network.mineNextBlock function, and feed it the transactions we created on lines 4–7. This will make the miners in the network try to mine a new block, and add these transactions to that block. The callback is called when one of the miners in the network has successfully mined the block.

Having come this far you actually have the core concepts of a blockchain down. Addresses make transactions which are picked up by miners who put them in blocks which are added to the blockchain.

The next part of this tutorial guides you through the implementation of the Blockchain. For this part we’ll go into some more advanced topics like Proof-of-work, SHA256 hashing and broadcasting new blocks to the network of miners.

Step 3 — Creating the blockchain

I’ve called the project “Lightchain” and it can be found on GitHub. The neat part is that it will run in your web browser, so no dependencies or NPM installs are needed. Instead Lightchain uses web workers for its miners to concurrently try to mine new blocks. So this blockchain is in no way connected to other computers, it’s mainly a demonstration of how the concepts behind a blockchain work.

Don’t get discouraged if the amount of code in this article seems lengthy, the entire implementation on GitHub is under 140 lines of code!

Step 3a - let’s create the block!

Each block needs a

  • previousHash - defaults to 0 for the genesis block
  • timestamp - defaults to current date
  • transactions - transactions that should be stored in the block
  • nonce - an integer which is incremented every time the miner tries to mine the block (https://en.bitcoin.it/wiki/Nonce)
  • hash - the SHA256 hash of this new blocks’ previousHash + timestamp + transactions + nonce
  • difficulty - the block difficulty, which determines how hard it is to mine a new block
  • #calculateHash - this function returns the SHA256 hash of the block content

Step 3b - creating the address

An address is very straight forward and contains two fields:

  • address - the name of the address, a string which can be set to anything
  • balance - the initial balance of the address

Step 3c - creating the transaction

A transaction is also very simple and contains three fields:

  • from - the address this transaction sends coins from (has to be an Address object)
  • to - the address this transaction sends coins to (has to be an Address object)
  • amount - the number of coins that should be sent

Step 3d - the miner implementation

Alright so the code for the miner can seem tricky, but is intuitive if you have read step 1 & 2 of this article. A miner is connected to other computers in a real blockchain, but in our proof of concept, it’s just part of an array of miners:

  • name - the name of this miner, a string which can be set to anything
  • blockchain - the copy of the blockchain that every miner needs to have
  • #mineBlock - this function takes a list of transactions and tries to mine a new block. It first runs JSON.stringify(newBlock.transactions) to write the transactions to the block, and then increments the nonce as a way to try to find a SHA256 hash which starts with 0 to n (block.difficulty) leading zeros. So if the block difficulty is for instance 4, then incrementing the nonce until the hashed block starts with 4 zeros makes you successfully mine the block. The string “https://cdnjs.cloudflare.com/ajax/libs/js-sha256/0.9.0/sha256.min.js" is a reference to the SHA256 library that we need to access inside the web worker, and we’re using Operative (https://github.com/padolsey/operative) to create new web workers for each mining process. The mineBlock function also takes a callback, which is called then the block has been successfully mined.
  • #isValidNewBlock - this function validates a new block against the latest block in the blockchain. The new blocks’ hash needs to be the same as the previous blocks’, and we also run the hash function for good measure. This is one of the core concepts of blockchain technology; each new block needs to contain the hashed data of the previous block, otherwise the block will be rejected by the network.

Step 3f — the blockchain

The blockchain is another pretty simple implementation;

So the job of the blockchain (at least in this implementation) is to hold the block data, and two convenience methods.

  • blocks - the blocks the blockchain consists of. At this point of the tutorial you should have an understanding of how blocks work, so you can for instance follow the blocks of the Bitcoin network https://blockchain.info/
  • #getLatestBlock - get the latest valid block of the blockchain; convenience method for when you want to compare new incoming blocks to the latest valid block
  • #getAddressBalance - so here’s a mind-blowing fact that I only understood after having coded a blockchain myself, addresses don’t really hold coins. And as you can see in this implementation, getting the balance of an address means iterating through all of the transactions the address has been involved with, and counting the result of the transactions. For more information on how an address actually works in the Bitcoin network, see this link https://en.bitcoin.it/wiki/Address

Step 3g - the network

So in the last part of our blockchain, we’ll create a network whose job it is to connect all the miners, trigger them to mine a new block and broadcast said block to the rest of the network.

  • miners - the miners are added to the network so that they are aware of each other and can broadcast new blocks when they are found
  • #mineNextBlock - this function takes unconfirmed transactions (that you want included in the blockchain), and puts them in line to be mined. As you can see it calls miner#mineBlock for each miner so that they all race to find the correct hash of the new block. The miner which finds the hash first will call network#broadcastToNetwork
  • #broadcastToNetwork - when a miner has successfully mined a block, it will broadcast that block to the rest of the miners. The miners then each run #isValidNewBlock to see if it is actually valid. If they’ve all validated the block it is added to each miners’ copy of the blockchain.

Step 4 - Conclusion

So that’s it, if you’ve finished reading to this point, then you probably know more about blockchain than 99% of the worlds’ population.

I wrote this article because I find blockchain technology intriguing. It contains many aha moments, and manages to fit simple ideas so naturally together and form a greater whole.

If you liked the article and want to see all of the code in one place, go to:

Thanks for reading!

References:
https://www.savjee.be/2017/07/Writing-tiny-blockchain-in-JavaScript/
https://medium.com/@lhartikk/a-blockchain-in-200-lines-of-code-963cc1cc0e54

--

--