Learn blockchain by building a blockchain application!

This article was first published on the WeChat public account of “Wanyun Wancloud” under Wanxiang Blockchain.

As soon as the door opened in 2018, the fire of the blockchain burned into a mountain of flames. Xu Xiaoping promised to embrace the blockchain, and the circle of friends was constantly swiping. He could even hear the blockchain on the subway at work. From the beginning of the night, the blockchain became the talk of the tea before and after dinner. So, the often-heard question started scratching its head again: what the hell is a blockchain? The subscription accounts you follow keep pushing different content such as "an article to make you understand the blockchain", "Get blockchain in three minutes", and the voices focus on your ears from all directions.

Wan Yun is also thinking about what he can do for the old irons who want to understand the blockchain. Since there are so many popular articles on blockchain concepts, this time we will not talk about boring concepts, but return to blockchain "technology" , teach you step by step to get a blockchain of your own. Rest assured, as long as you know a little bit of technology, you can implement and have it.

 

|| The following translation is from "Learn Blockchains by Building One" by Daniel van Flymen, with some changes.

|| Original address: https://hackernoon.com/learn-blockchains-by-building-one-117428612f46

 

foreword

Conceptual understanding: Before you start, you need to know that the blockchain is a chain data structure that combines data blocks in a sequential manner according to time, and ensures its untamperable and unforgeable distribution through cryptography ledger. These blocks can contain transactions, files, and whatever data you want, the important thing is that they are linked together by hashes.

Target audience: Can easily read and write some basic Python and have some understanding of HTTP.

Required tools: Python 3.6+, Flask, Requests:

pip install Flask==0.12.2 requests==2.18.4

In addition, you need to install HTTP tools, such as Postman, cURL.

Source code address : https://github.com/dvf/blockchain

 

Step 1: Build the blockchain

① Implement a Blockchain class

Open a text editor or IDE you often use, create a new blockchain.py python file, and create a Blockchain class. In the constructor, create two empty queues, one for storing the blockchain and the other for storing trade. Below is the template code for the Blockchain class:

 

The Blockchain class we created will manage the chain, it will store transactions, and provide methods to help add new blocks to the chain. The following is the detailed implementation method.

Each block contains 5 basic properties : index, timestamp (in Unix time), transaction list, proof of work and the hash value of the previous block. Let's look at an example:

 

At this point, we should be clear about the concept of chain, each new block will contain the hash value of the previous block, so that the blockchain has the characteristics of immutability. If an attacker attacks earlier blocks in the chain, all later blocks will contain incorrect hashes. If you can't understand it, digest it slowly - this is the core idea of ​​understanding blockchain technology.

 

②Add the transaction to the block

Next we implement a method to add transactions to the block, continue to look at the code:

 

After adding a transaction to the list in the new_transaction() method, its return value is the index of this transaction, which will be added to the next block to be mined and will be used later when the user submits the transaction.

 

③Create a new block

When the Blockchain is instantiated, we need to create a genesis block and at the same time add a proof-of-work to our genesis block, which is the result of mining, which we will discuss in detail later.

In addition to the code to create the genesis block, we also need to add new_block(), new_transaction() and hash() methods:

 

At this point, our blockchain has basically achieved its prototype. At this point, you must want to know how new blocks are mined, which is what we usually call "mining".

 

④What is Proof of Work?

To understand what "mining" is, you must understand what proof-of-work (POW) is. Every new block on the blockchain comes from proof of work (POW). The goal of POW is to calculate a series of numbers that solve the problem. This result is notoriously difficult to calculate, but it is very easy to verify because the network Anyone on the Internet can verify this result, which is the core idea behind "Proof of Work".

Let's look at a very simple example to help understand:

Assuming that the hash of an integer X multiplied by another integer y must end in 0, hash(x * y) = ac23dc...0. Let x = 5. Find y. We do this in Python:

 

The answer is that when y = 21, the hash value ends at 0:

 

In Bitcoin, the proof-of-work algorithm is called Hashcash, which is similar to our example above, and turns out to be hard to find but easy to verify. Hashcash is a problem that miners compete to calculate in order to create a new block. The calculation difficulty usually depends on the number of characters searched in the string, and it usually takes a certain amount of time to calculate. The final calculated miners will obtain a certain amount of money through the transaction. Amount of Bitcoin as a reward.

 

⑤ Implement a basic proof-of-work

First we implement a similar algorithm for the Blockchain class:

Rule: Find a number p such that the hash value of the string concatenated with the proof of the previous block starts with 4 zeros.

 

The difficulty of the algorithm can be adjusted by modifying the number of leading zeros, but 4 zeros are perfectly sufficient. You will find that every time you add a leading zero, it makes a huge difference between the time it takes to find a corresponding solution and the time it takes.

At this point, our Blockchain class has been basically completed, and then we implement the HTTP service for interaction.

 

Step 2: Blockchain API

We will use the Python Flask framework, Flask is a lightweight web application framework that allows us to call Blockchian classes through web services.

 

①Create three APIs:

• /transactions/new creates a new transaction for the block

• /mine tells our server to mine new blocks.

• /chain returns the entire blockchain.

 

②Use Flask

Our "server" will be based on the Flask framework to implement a node in the blockchain network. Let's add some template code:

 

Here is a brief description of what was added above:

Line15: Instantiate the Flask web service node.

Line18: Create a random name for our service node.

Line21: Instantiate the Blockchain class.

Line24-26: Create a GET request with the route /mine and call the new block method of the backend Blockchain.

Line28-30: Create a POST request with the route /transactions/new and send the data to the new transaction method of the backend Blockchain.

Line32-38: Create a GET request routed to /chain that will return the entire chain.

Line40-41: Running the server on port 5000.

 

③ Realize the transaction

Below is the request sent to the server when the user initiates a transaction:

 

Since we already have a way to add transactions to the block, the next step is easy.

Let's implement the function to add a transaction:

 

④ Realize mining

Our mining method is where the magic happens. It's very easy and only does three things: calculate the proof of work; reward the miner with a certain amount of bitcoin by adding a transaction; create a new block and add it to the chain.

 

It should be noted that the transaction receiver of the mined block is the address of our own server node. Most of the work we do here is just interacting with the Blockchain class. Based on the above, our blockchain has been completed, and then we will start the interactive demonstration .

 

Step 3: Interactive Demonstration

You can use cURL or Postman to interact with the API.

Start the server:

 

Try mining a block by making a GET request to http://localhost:5000/mine:

 

To create a new transaction, make a POST request to http://localhost:5000/transactions/new:

 

It is also possible to send requests using cURL:

 

The above are just examples of interactive demonstrations, you can try more on your own completed blockchain.

 

Step 4: Consensus Mechanism

We have a basic blockchain for transactions and mining, but blockchains are more important because they are distributed. Then we need to ensure that all nodes are running on the same chain, which is a return to the consensus problem. If we want to meet the requirements of having multiple nodes on the network and keep increasing, we must implement a consensus algorithm.

 

①Register a new node

Before implementing a consensus algorithm, a way needs to be found for nodes on the network to know its neighbors, and each node needs to store the records of other nodes on the network. Therefore, we need to add a few new methods to help achieve this:

1. /nodes/register accepts a list of new nodes in URL form.

2. /nodes/resolve to execute our consensus algorithm, which resolves any conflicts ensuring nodes have the correct chain.

 Below we will modify Blockchain's constructor to provide a method for registering nodes:

 

Note that we use set() on the collection to hold the list of nodes, this is an easy way to ensure that the addition of new nodes is idempotent, meaning that no matter how many times we add a particular node, it will only appear once.

 

②Implement consensus algorithm

As mentioned earlier, conflict occurs when one node is different from another node. In order to solve this problem, we follow the principle of taking the longest chain. By using this algorithm, the nodes in the network can reach a consensus.

 

valid_chain() is responsible for checking whether a chain is valid by reading each block in a loop and verifying the hash and proof.

resolve_conflicts() is responsible for looping through all adjacent nodes, getting their chains and verifying their validity using the method above. If a longer valid chain is found, replace our current chain.

We register two methods into our API, one for adding adjacent nodes and one for resolving conflicts:

 

Finally, if you want you can spin up another machine and run a different node on your network. Or start the process using a different port on the same machine. I create another node on a different port of my machine and register it with the current blockchain network. So I have two nodes: http://localhost:5000 and http://localhost:5001.

 

To make sure the chain is longer, I mine some new blocks on node 2. After that, I call GET /nodes/resolve on node 1, where the chain has been replaced by the new chain calculated by the consensus algorithm.

 

Now, you can invite some friends to test your blockchain together.

 

This is the end of this tutorial. So, is your own blockchain ready? Don't forget to share it with your friends who are also programmers, let's play the blockchain together!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325856356&siteId=291194637