We’ll build a very simple POC blockchain with four distinct building blocks. Check the repo for reference!
Transaction
The only things really needed for a transaction to take place are:
- Who sends the money?
- Who receives the money?
- How much money?
Block
Think of a block as a group of transactions with a time stamp and a reference to the previous block:
As discussed before, we need to hash our blocks. To do this, we’ll use the crypto
library:
We create a SHA256
hash, add our stringified block to it, and output a hexadecimal
representation of it. This is what will link multiple blocks together.
Chain
Since there should only ever be one chain, we can represent it as a Singleton. We also know that it will host our blocks and that these need to know about their predecessor, so we can start by:
Let us also initiate the chain with a first block:
We’ll also need a way to add blocks to the chain. Something like:
This will work, but it allows anybody to send anything anywhere. We need verification, signatures and keys. We need a wallet.
Wallet
At a basic level a wallet is just a wrapper for a key pair, not unlike what you use to secure an SSH connection.
Again, we’ll use the crypto
library to generate the key-pair. Since we want two ways encryption, we’ll use RSA
.
Payment
As explained before, we don’t want to expose the private key nor the encrypted data. Rather, we use the private key to sign the data.
This way, the public key can be used to verify the data’s integrity without exposing the private key.
Here we create a transaction and use crypto to sign it with the payer’s private key. In a real world scenario we would verify the signature sending the block to various miners (nodes) over the web, but it’s good enough for our purpose.
We’ll have to update our addBlock
function to ensure the block is verified before being added to the chain:
Mining
As mentioned before, we’ll use of the concept of “Proof of Work” to our advantage.
Let’s add a POW seed to our Block
class:
Now we can add a mine
function to our Chain
such as:
Here we look for a number that added to the seed will produce a hash starting with four consecutive nines. The specific implementation here doesn’t really matter, as long as it is somewhat costly to compute.
After finding the correct answer (which will be different for each block) it will return it for the other nodes to verify (which is much easier than to solve), or at least that is what would happen in a real world application.
Run it
Hopefully you’ve ended up with something like this.
You can add your own finishing touches and run npm run start
to see it in practice.
There you go, your very own blockchain!