Understanding and creating Blockchains

Aurélio Buarque
Coinmonks
Published in
6 min readJul 26, 2018

--

Taken from: https://www.zdnet.com/article/what-is-the-future-of-blockchain/

I see a lot of blogs and people talking about blockchain but in a very superficial way. Ok, they explain that blockchain works as a ledger that handle transactions in such a safe way that violate it would be a very painful task, but that it’s too far away from a great understanding of blockchain for a software engineer.

I’m kinda Jack, the Stripper, so let’s go by parts: firstval, we’re gonna try to understand basic core concepts of blockchain, such as transaction, mining and proof of work. Then, we’re gonna implement one to see those concepts in practice.

Core concepts

If you studied computer science, you probably know an elementary data structure called linked list. Such data structure is made by a collection of nodes, or blocks, linked to each other by a reference and they store some kind of data, like integers, strings and so on.

Taken from: http://www.rubyguides.com/2017/08/ruby-linked-list/

A blockchain is pretty similar to a liked list: it’s a collection of nodes linked to each other, but different from linked lists, they are linked by a kind of key (hash). That is, each node has its own hash and also the hash of a neighbor node. As that Paramore’s song would say, the only exception is the first node of chain, called genesis block.

Taken from: http://racenext.com/blockchain.html

Whenever a new blockchain is created, the genesis block should be created too. And the main information that those blocks stores are transactions. A transaction could be a restaurant payment, a bank transfer, a booking in a hotel or any other desired situation.

Backing to linked lists, to insert data inside of it, we just need to create a new node, put some data inside of that node and add it to the list. With blockchains the process is pretty similar too, the difference is that you cannot just create a new block, you must ensure that the created block took a lot of work to be made, that is, the process was difficult. That process ensures a proof of work to the block, and it’s called mining, due to the fact we had to not only create a block, but also find a proper one. Soon you’ll see in practice why it demands so many computational power.

As mentioned before, the main data stored in blocs are transactions, and there’s something interesting on that: transactions should be created in a certain time interval instead of every time, because doing that it’s possible to implement a kind of reward system for miners in such a way that when a new block is mined they gain some points, while the other transactions are pushed into a list to be handled.

Implementation

Read about those concepts without any practice doesn’t make much sense, so let’s create a Java Script project using ES6 features and take a deep look. First, create the project called blockchain:

mkdir blockchain
cd blockchain
npm init -y
touch index.js
npm install --save babel-register
npm install --save-dev babel-preset-es2015
npm install crypto-js
touch .babelrc

Inside the .babelrc file add the following content:

{ “presets”:[“es2015”] }

And at the package.json file, in scripts area add it:

"start": "babel-node index.js"

Now we’ve got ES6 enabled in our project.

Essentially, we’ll have only three models in this project: Transaction, Block and Blockchain. The first one is a blueprint for a possible real word transaction, where someone sends money to other one.

Block is a component of blockchain. I has a time stamp from the moment it was created, the hash of previous node, its own hash and a list of transactions.

The method getHash() just uses the block attributes to create a hash. And as we don’t control its return we can take advantage of it to add a proof of work to mining. If you take a look into the mine method you’ll see in line 17 that there’s a variable called patternOfDifficulty and the idea is pretty simple: we create a block with some value of hash, the return of getHash() method, then we check if the first difficultydigits (being a string with a quantity of 9s in our case equals to difficulty) are equal to the defined patternOfDifficulty. If it’s not, we keep it running till the condition gets false, that is, the first difficultydigits are equal to patternOfDifficulty. So for example, suppose we get the following hash:

232#4533829jmz-2038282s21332dshjaxjhajhuaghahdkvacadhakhdkahdk338283

And if our difficulty is equals to 4 the patternOfDifficulty would be:

9999

If we get the first “difficulty” chars of the hash we get:

232#

And comparing with the patternOfDifficulty:

9999 != 232#

We get false. So we need to make it again. If the gotten hash now is:

9999jfknejfwhfkwnfkwhkfihiemht7et97-29u3oh38hfoahgufgaouyf7g7g7g7g

The first “difficulty” chars now are:

9999 

And if we compare with patternOfDifficulty:

9999 == 9999

They match, so we get out of the loop and we have mined a block. The higher the difficulty, higher is the time to mine a block. If you take a look again to the Block class you’ll see at line 9 the attribute changeable, that attribute is responsible to change the output of the SHA256 function, because all the others attributes never change inside the loop. Due to that, in order to provoke a different output of that function, the value of changeable is incremented every iteration.

Once we have the Transaction and Block classes we can implement the BlockChain class:

As you can see that class holds a list of blocks and pending transactions. It also has an attribute to specify the mining difficulty and the reward for a miner.

Inside the constructor, in line 3, when we declare the blocks list we already add a block, the reason was already said above, that one is the genesis block. That block is create by the getGenesisBlock() method defined at line 9. That method just returns a Block instance without a prevHash attribute.

With that stuff we can start playing: let’s create a blockchain called fancyChain with difficulty 2 and 100 as mining reward. Then we’re gonna insert two transactions inside of that chain, where someone with id 505 sends to someone with id 40 an amount of U$$ 100,0 and them U$$ 150,0 dollar. Take it as a situation where someone is buying something from its friend and our chain is registering the transaction.

If we print the fancyChain as a JSON:

As you can see it’s working as expected: our chain was created with the genesis block and the two transactions are placed there. Now let’s suppose that someone with id 31 tries to mine some pending transactions and see its balance after the mining:

By doing that our output would be:

If take a look on those hashes you’ll see the first two characters (difficulty = 2) are 99, as we’ve define creating our block chain instance before. And printing the chain again we get:

Taking a look again you’ll see also that all those blocks, except from the Genesis, stores the hash of a previous block.

Now it’s time to see why blockchain is so safe for registering transactions. Suppose that friend of id 40 is actually a thug, and he tries to change the transaction value to a higher value, like that:

Doing that something interesting happens to the blockchain: all the chain gets invalid. You can check it by doing the following:

console.log(“Is fancyChain valid? “ + fancyChain.isChainValid());

If you take a look back in the BlockChain class the method isChainValid() will explain: once the value of the transaction was changed the if statement at line 49 will get false, because the method getHash() is called and it uses the transactions array to get its hash. Thus, by just changing that value all the chain gets invalid.

That is one the reasons that blockchain is a very safe tool to registering transactions and build smart contracts.

Summarizing

Blockchain can be very useful if you want to create your own crypto coin, smart contracts or deal with transactions in a safe way.

As you saw, a blockchain is basically a collection of blocks that stores transactions that someone can mine and earn some kind of points.

As advice, I should say to you do NOT use this example for a real crypto system, the intent here is just tell you about blockchain with a deeper software understanding. As a tip for you, I’d suggest to you change the difficulty of the blockchain and see how many time takes to you mine a block in your computer : )

That’s all, till next!

Code on GitHub: https://github.com/ABuarque/BlockchainArticle

--

--