I've been hearing about Blockchain for at least 10 years. And look, I heard about it late.
The concept of Blockchain dates back to the 90s and comes from the Xerox laboratories in Palo Alto, California. Yes, the same laboratory that invented the mouse and the graphical interface in the 70s. The guys are good there, see...
Despite being a “nineteenth-century” concept, its first practical and famous application was with the invention of Bitcoin in 2008, by Satoshi Nakamoto. Although Satoshi himself does not mention the term “blockchain” in his white paper explaining Bitcoin the terms blocks and chain are mentioned several times, giving rise to the term as we have known it ever since.
But finally, what is blockchain then? How does it work? How is a blockchain programmed?
In an attempt to answer these questions, I wrote this article, which later on should become a practical tutorial, right after the fundamentals.
What is Blockchain?
- The first thing you have to understand is that blockchain is a type of database but it is not an ordinary database, it has some unique features. The first is that instead of tables and columns, it has blocks that interconnect, forming a chain. Each block has various information inside, which we will talk about below, but mainly, every block has a reference to its previous block, called a hash. This reference is extremely sensitive and if the previous block changes, it becomes “invalid”.
- Therefore, the second characteristic is that it is an immutable database, that is, you can consult and add data at will, but never remove or edit it. This is because being a chain of blocks, any attempt to change an existing block would break the reference between the blocks and consequently the chain. So you can only add new blocks at the end.
- The third characteristic is that it is decentralized, that is, it is not located on just one server, but on several nodes (nodes) that work in cooperation to keep the blockchain online, safe and functioning. Nodes can freely enter and leave the network and as long as at least one node is online, the blockchain will remain in operation. The functioning of blockchain consists of continually adding new data (which can be data from anything) or validating the network. Nodes that record data on the blockchain are called miners and they are rewarded with tokens or coins from the network itself when they successfully carry out this activity.
In the case of the “original” blockchain, Bitcoin, we can add a fourth feature, which is the fact that it is public, but this is not a rule in all blockchains, and there may be private blockchains that involve sensitive data from governments and companies. This is because although the Bitcoin blockchain only records transactions with the currency of the same name, blockchains like Ethereum and other more modern ones allow the recording of any type of information, what we usually call Smart Contracts in blockchain jargon. But if you want to complete this more theoretical step by having a look at a visual tool that simulates all the parts that make up a blockchain, you can use this blockchain simulator by Anders Brownworth. It's really cool because it goes from the most elementary concept of hashing to distributed blockchain, so you understand how it works and especially the security involved.
What is in a Blockchain Block?
To explain it in a way that you really understand, I propose the challenge of trying to implement a blockchain together, from scratch, using JavaScript. Of course, it will be a prototype and for educational purposes only, but I'm sure it will help a lot to make the understanding of how a blockchain works clearer. To do this, you need to have Node.js installed on your machine, which you can download for free from the official website.
To create the project, it's very simple, create a folder called blockchain and inside it run the project initialization command.
npm init -y
As mentioned before, the most elementary piece of every blockchain are the blocks, so that's where we'll start. As we will need to have several blocks, but they all have the same structure, it makes a lot of sense to use classes for this. So let's create a Block class at the root of our project.
But what would be the attributes of this class? Every block needs:
- index: the block number;
- previousHash: the hash of the previous block;
- data: the block data (can be transactions, Smart Contracts, etc.);
- timestamp: the date and time stamp that this block was generated;
- hash: the digital signature of this block, generated from all previous data;
Translating this information into a JS class is very simple, as follows, and I intentionally left the hash part incomplete:
module.exports = class Block {
constructor(index = 0, previousHash = null, data = 'Genesis Block') {
this.index = index;
this.previousHash = previousHash;
this.data = data;
this.timestamp = new Date();
this.hash = null;
}
module.exports = class Block {
constructor(index = 0, previousHash = null, data = 'Genesis Block') {
this.index = index;
this.previousHash = previousHash;
this.data = data;
this.timestamp = new Date();
this.hash = null;
}
}
Note the default values that represent the state of the “genesis block”, which is always the first block in the entire blockchain. It has index 0, has no previous hash and its data is just the indication that it is said-whose. There is another default data in the middle, which is the timestamp, which will always be the current date of creation of the block.
Now, we have to implement the generation of the hash of this block, its digital signature. To do this, we will need to install an additional package in our project, crypto-js, a library full of implementations of useful encryption algorithms.
npm i crypto-js
Now let's reference this lib in our Block.js module and within it we will call a new hash generation function from all the block's internal data.
const sha256 = require('crypto-js/sha256');
module.exports = class Block {
constructor(index = 0, previousHash = null, data = 'Genesis Block') {
this.index = index;
this.previousHash = previousHash;
this.data = data;
this.timestamp = new Date();
this.hash = this.generateHash();
}
generateHash() {
return sha256(this.index + this.previousHash + JSON.stringify(this.data) + this.timestamp).toString();
}
}
In other words, when creating the block, we automatically calculate its hash, so that it can be added to the chain. The hashing algorithm used here was SHA-256, recommended by Google and considered one of the fastest and most secure by current standards. Still, it could be replaced by different algorithms, depending on the blockchain architect's interest.
Note that the data attribute can be anything, as previously mentioned and I am adopting here the use of a JS object for it, which is explicit in the function of generating the hash in which I transform it into a string through JSON.stringify.
Try creating an index.js and instantiate some Blocks, like below, just to play in a console.log and see what was generated. It will help you better understand the anatomy of a block.
const Block = require("./Block");
const block1= new Block();
console.log(block1);

Even try creating blocks by passing or not the constructor parameters and you will see that even if the difference in the data is just one letter, your digital signature will always be almost completely different.
How are Blocks Linked on the Blockchain?
Now that we've learned how to create a block, how about we create a chain of them?
This can be done either using classes or using a simple JS module, as it is not common for a blockchain project to be created in parallel. Still, I believe that an object-oriented solution (with classes) is more elegant due to some default behaviors that are necessary.
So, what should there be attributes in a Blockchain class?
- blocks: an array of blocks that can grow indefinitely and that starts with the genesis block;
- nextIndex: the next index of the array where we can add a new block;
Of course, this is to start talking about blockchain and the implementation below is purposely simple for our first tests, put it in a Blockchain.js file.
const Block = require('./block')
module.exports = class Blockchain {
constructor() {
this.blocks = [new Block()];
this.nextIndex = 1;
}
getLastHash() {
return this.blocks[this.blocks.length - 1].hash;
}
addBlock(data) {
const hash = this.getLastHash();
const block = new Block(this.nextIndex++, hash, data);
this.blocks.push(block);
}
}
In this naive implementation, the block array is initialized with the genesis block right at the creation of the blockchain and the index of the next block to be added is set to 1 (since the first receives position zero). We have also already placed a function to add a new block to the chain, just receiving its data, since the other information is automatic (timestamp for example) or managed by the blockchain (index for example).
You can easily test this class in your index.js by creating a blockchain from scratch and adding blocks to it.
const Blockchain = require("./Blockchain");
const blockchain = new Blockchain();
blockchain.addBlock([{ from: 'a', to: 'b', amount: 10 }]);
console.log(blockchain);

Note that I chose to use an array of transactions as data. In each transaction we can tell who (from) is sending money (amount) to who (to). Optionally, you can create a Transaction class to more elegantly record transactions and the from and to values in a cryptocurrency situation would be the wallet addresses (which are unique hashes for each user).
In a real blockchain, addBlock should also record the data on disk, so as not to just depend on storing everything in memory, and at its initialization should fetch this already saved data so as not to always start from scratch. In a distributed and decentralized situation, there are still other complications, which I hope to talk about in the future as well.
In the second part I'll discuss how are blocks validated and what prevents fake blocks from being added to the Blockchain, so stay with me and don't forget to like and follow!