Simple blockchain from 40 lines of code

Tram Ho

Back more than 20 years ago, the arrival of the internet was considered a revolution in the world. The Internet helps us to update information at any time anywhere in the world, changing the whole landscape for the whole world in general and journalism and media in particular. And at the present time, there is a new revolution like the internet of more than 20 years ago, experts and analysts mentioned banking and finance – blockchain technology.

After 20 years, what caused the world to look once again as a new revolution?

Blockchain – According to Google search, “Blockchain: a digital ledger in which transactions made in bitcoin or another cryptocurrency are recorded chronologically and publicly”. It can be roughly understood as a digital ledger, in which transactions are strictly monitored.

In this article as its title, we will not go into what is Blockchain? And if you are reading this article for the first time hearing about Blockchain or are quite ambiguous about it please take some time “ctrl + N” open a new tab and learn more offline! We will create a simple Blockchain with less than 50 lines of Python code .

1. The most basic blockchain

We will start by determining what the blocks will look like. In the blockchain, each block will be organized and managed according to a timeline and index code. In this small application, we will store both, and to ensure integrity during operation, each block will have a corresponding identifying hash code. Like bitcoin, the block’s hash code will be a security code for the block’s own index code and also the timestamp, data and hash of the previous block. Depending on the application will have different data to store.

We have just defined a block, to complete the Blockchain, we need to add the blocks to the actual chain. Each block will require authentication from the previous section. However, in order to work like that, we need to create the first block as the root. The first block we need to create manually. We write a function that initializes a root block. For simplicity, this block has an index of 0 and it has arbitrary data.

Next, we write the function that defines the next block

2. Add the Block to the Blockchain

Now we need a function to create new blocks. This function will take the previous block in the string as a parameter passed to create a new block. When new blocks are created with parameters passed from the previous block, the integrity of the blockchain increases. If we don’t do this, it’s easy to change the old blocks and replace the string with a brand new one.

Much of the work is done, now we finish the program and run to create the block.

3. Complete the program

Our blockchain will start with the block genesis defined above, we will add 20 blocks with the for loop:

Program results:

Full source code: Link Github

Reference: Techinasia (Gerald Nash)

Share the news now

Source : Viblo