Building A Blockchain Network From scratch With Python

Tram Ho

In today’s tutorial we will go from the first steps to building a simple blockchain network in python language. Giving us the best overview of how a blockchain works.

Using microframework Flask to create endpoints, then run on multiple machines to create a decentralized network. We will learn how to build a simple user interface to interact with blockchain and store information for every use case, such as peer-to-peer payments, chat or e-commerce.

The goal is to build an application that allows users to share information by posting posts. Content will be stored on the blockchain, so it will not be changed and exist forever. Users will interact with the application through a simple web interface.

We will use the bottom-up approach. Start by defining the data structure that we will store in the blockchain. Each post will include three essential elements:

  • Nội dung
  • Author
  • Timestamp

Here we will go into the steps:

Store transactions in blocks

Here we will store in the widely used format that is JSON. And here is what a post will be stored in the blockchain:

The term data in blockchain is often replaced by transaction . So here we agree to use the term transaction to refer to data in this application.

Transactions will be packaged into blocks. A block may contain one or more transactions. Blocks containing transactions are generated regularly and added to the blockchain. Because there are many blocks, each block will have a unique ID :

Add digital signatures to blocks

To prevent fake data from being stored inside the blocks and to detect this we will use the hash function.

A hash function is a function that takes data of any size and creates data of a fixed size, often used to determine input data. Ideal hash functions often have the following characteristics:

  • Easy to calculate.
  • The same data will always result in the same hash value.
  • There must be uniform consistency which means that even a single bit change in data will change the hash value significantly.

The results of these properties are:

  • It is almost impossible to predict the hashed input. (The only way is to try all possible input cases)
  • If you know both the input and the hash value, you only need to pass the input via the hash function to verify the provided hash value is correct.

There are various common hash functions. Here is an example in Python we use the SHA-256 hash function:

We will store the block’s hash value into a field inside the Block object and it will act like the digital signature (or signature) of the data contained therein:

Join blocks into chains

We need a way to ensure that any changes in the previous blocks will invalidate the entire chain. The way Bitcoin works is to create dependencies between successive blocks by stringing them with the block’s hash value immediately. This means saving the hash of the previous block in the current block when adding a new field to the previous_hash .

There will be a question: what about the first block? That block is called the genesis block and it can be created manually or through some logic.

Now, if the contents of any previous blocks change:

  • The hash of the previous block will change.
  • This will result in mismatch with the previous_hash field in the next block.
  • Because the input data to calculate the hash value of any block also includes the previous_hash field, the hash value of the next block will also change.

In the end, the whole chain as a replacement block is disabled and the only way to fix it is to recalculate the entire chain.

Implementing the Proof-Of-Work algorithm (Proof of Work)

The problem, though, is that the hash value of all subsequent blocks can be easily recalculated to create another valid blockchain. To prevent this, we can exploit the asymmetry of the hash function we discussed above to make the task of calculating the hash value more difficult and random. What this means: Instead of accepting any hash value for the block, we add some constraints to it. Let’s add a constraint that our hash value will start with n leading zeros where n is a positive integer.

Here we will add some dummy data that we can change. We will add a new field which is the nonce field. The nonce number is a number that we can keep changing until we have a constrained hash function. The fact that the nonce satisfies the constraints acts as evidence that some calculations have been performed. This technique is a simplified version of the Hashcash algorithm used in Bitcoin. The number of zeroes specified in the constraint determines the difficulty of the PoW algorithm (the greater the number of zeroes, the harder it is to find nonce).

Also due to the asymmetry, Proof-of-work (PoW) is difficult to calculate but very easy to verify once you find the nonce (you just need to run the hash function again):

Add blocks to the Chain

To add a block to the chain, we must first verify that:

  • The data is not tampered with (proof of work provided is accurate).
  • The order of transactions is kept the same.

Mining

The original transactions will be stored as a group of unconfirmed transactions. The process of putting unconfirmed transactions into a block and calculating the POW is called Mining blocks. When the nonce that meets the constraints is found, we can say that a block has been mined and it can be put into the blockchain.

In most cryptocurrencies (including Bitcoin), miners can be given a number of cryptocurrencies as a reward for using their computational power to calculate POW. Here is the function mining:

Ok this is the code of the processing: source code

Create the interface

In this section, we will create the interface for the blockchain node to interact with the application we have just built. Here will use a popular Python microframework called Flask to create interactive REST APIs and invoke various actions in our blockchain node. If you’ve worked with any previous web framework, the code below won’t be hard to follow.

We need a route for the application to create a new transaction and this is the post

There will be a route that returns a copy of the chain. And this route the application will use to query all data to display:

And here is the route to send a mine request – validating unverified transactions (if any). We will use it to start a mine command from our own application:

Establish a consensus and dispersion mechanism

There is a blockchain problem that we have deployed running on a computer. Although we have linked the blocks with the hash value and applied POW, it is still not possible to trust a single entity (in this case, a single machine). We need distributed data or multiple nodes to maintain the blockchain. So, to move from a single node to a peer network, let’s first create a mechanism so that a new node can learn about other peers in the network:

A new node joining the network can call register_with_existing_node to register with existing nodes in the network. This will help the following:

  • Request the remote node to add a new peer to the existing peer list.
  • Easily Initialize blockchain of new node by retrieving remote node.
  • Re-sync the blockchain to the network if that node is no longer connected to the network.

However, there is a problem with many nodes due to intentional or unintentional reasons (such as network latency), the chain copy of several nodes may be different. In that case the nodes need to agree with some version of the chain to maintain the integrity of the entire system. In other words, we need to reach a consensus.

A simple consensus algorithm can agree with the longest valid chain when the chains of participating nodes in the network appear forked. The reason behind this method is that the longest chain proves the most work done (remember PoW is very fastidious):

Next we need to develop a way for any node to inform the network that it has mined a block so that everyone can update their blockchain and move on to mining other blocks. Other nodes may only need to verify the PoW and add the newly mined block to their respective chain (remember that verification is easy when knowing the nonce):

The announce_new_block function should be called after each block is mined by nodes so other peers can add it to their chain.

Build web application

So the blockchain server is set up. You can see the source code here .

Now it’s time to start developing the web application interface. We have used the Jinja2 template to display views and some CSS to make things look good.

The application needs to connect to a node in the blockchain network to fetch data and also to send new data.

fetch_posts function:

The application has an HTML form to enter the user input and then makes a POST request to the connected node to add transactions to the unconfirmed transactions group. The transaction is then mined by the network and finally fetched after reloading the page:

Run the application

Here we have it! source code

Place to place:

Run a blockchain node on port 8000

run the web application:

The application will run at http: // localhost: 5000 .

Run multiple nodes

We will run multiple nodes by running on different ports. And use register_with to register as a peer network:

You can run the application (python run_app.py) and create transactions (post via web interface) and when you mined transactions, all nodes in the network will update the chain. And nodes can also be checked by calling with cURL or Postman.

Authenticate transactions

You may have noticed an application flaw: Anyone can change the name and post any content. Also, posts are easily fake while sending transactions on the blockchain network. One way to solve this is to create a user account, using the public key cryptography. Each new user needs a public key and a private key to post in the application:

  • Each newly sent transaction (post post) is signed with the user’s private key. This signature is added to the transaction data along with the user information.
  • During the verification phase when mining transactions, we can verify that the requested owner of the post is the same as the owner specified in the transaction data and the message is not modified if incorrect. This can be done using the signature and the public key of the owner who submits the post.

conclude

This tutorial covers the fundamentals of a public blockchain. If you’ve followed that up, you can now deploy a blockchain from scratch and build a simple application that allows users to share information on the blockchain. Hopefully the article will bring you useful and very interesting knowledge and see you in the next article.


Source : https://developer.ibm.com/tutorials/develop-a-blockchain-application-from-scratch-in-python/
Share the news now

Source : Viblo